NodeJS multer -请求文件未定义,

mpbci0fu  于 2022-12-12  发布在  Node.js
关注(0)|答案(7)|浏览(137)

我正在创建一个应用程序使用节点,快递和Handlebars和multer上传图像。每次我提交的形式,req.文件是未定义的。我花了一整天的故障排除,但不能找出我做错了什么。

路由器文件:

const express = require('express');
const router = express.Router();
const multer = require('multer');
const mongoose = require('mongoose');
const path = require('path');
const methodOverride = require('method-override');

//Set Storage Engine
const storage = multer.diskStorage({
    destination: './public/uploads/images',
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + 
    path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage
}).single('featuredImage');

//Change Featured Image - POST
router.post('/saveImage/:id', (req, res) => {
    console.log(req.file);

    //removed the rest of the code to keep it simple. req.file here is always undefined.

});

表格

<form action="/saveImage/{{pitch.id}}" method="POST" enctype="multipart/form-data">

    <div class="form-group">
        <label for="featuredImage">Featured Image</label>
         <input type="file" name="featuredImage" id="featuredImage">
     </div>

     <input type="submit" value="SAVE">
</form>

app.js这些要求位于app.js文件中。

const express = require('express');
const exphbs  = require('express-handlebars');
const path = require('path');
const passport = require('passport');
const mongoose = require('mongoose'); 
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const session = require('express-session');
const methodOverride = require('method-override');
const nodemailer = require('nodemailer');

//Set StaticFolder
app.use(express.static(path.join(__dirname, 'public')));
ff29svar

ff29svar1#

您需要添加upload.single('featuredImage')作为相应路由的中间件,如下所示。
const upload = multer({storage: storage});

//Change Featured Image - POST
router.post('/saveImage/:id',upload.single('featuredImage'), (req, res) => {
    console.log(req.file);

   //removed the rest of the code to keep it simple. req.file here is always undefined.

});
oalqel3c

oalqel3c2#

在我的情况下,这是与图像大小的问题。我解决了它与定义multer限制如下:

const upload = multer({ storage: storage, limits: { fieldSize: 10 * 1024 * 1024 } }); //10MB

我花了很长时间才弄明白也许这能帮到某人

1cklez4t

1cklez4t3#

请参考这个问题。它有您正在寻找的答案。
节点js multer文件上载不工作。req.file和req.files始终未定义

2w3rbyxf

2w3rbyxf4#

必须通过中间件

router.post('/saveImage/:id', upload.single('featuredImage'),  (req, res) => {
    console.log(req.file);

});
cgvd09ve

cgvd09ve5#

一开始我也有同样的问题!但当我补充说:

const { storage } = require ('debug/src/browser');

......成功了。
这是我的莫特代码:

const { storage } = require('debug/src/browser');
 
const multer = require('multer');

const MINE_TYPES = {
'image/jpg' : 'jpg',

'image/jpeg': 'jpeg',

'image/png':'png'
}

const Storage = multer.diskstorage({

destination: (req, file, callback)=>{

callback(null, "public/images/articles")

},

filename: (req, file, callback) => {

var name = Math.floor(Math.random() * Math.floor(15258652325)).tostring() 

name = Math.floor(Math.random() * Math.floor(15258652325)).toString();

name = Math.floor (Math.random() * Math.floor(15258652325)).toString();

name = Math.floor(Math.random() * Math.floor(15258652325)).tostring();

name = Math.floor(Math.random() * Math.floor 
(15258652325)).toString();

name += Date.now();

const extension = MINE_TYPES[file.mimetype]; 

name += extension;

callback(null,name);

module.exports = multer({ storage: Storage)). 
single('image');
byqmnocz

byqmnocz6#

我也遇到了同样的问题,您可以按照以下步骤解决它:
1-首先在server.js或index.js根文件中添加以下行

app.use(express.json());
 app.use(express.urlencoded({
  extended: true,
  })
 );

2-创建一个名为middleware的文件夹,并在其中创建一个名为upload.js的文件或任何您想要的名称。
3-将以下代码放入upload.js文件中

const multer = require("multer");

 const storage = multer.diskStorage({
 destination: function (req, file, cb) {
 cb(null, "public/");
},

 filename: function (req, file, cb) {
 const imgName = file.originalname;
 cb(null, imgName );
 },
});

 const upload = multer({
 storage: storage,
  });

module.exports = upload;

4-现在您可以在任何路由中使用此中间件。例如:

const upload = require("../middlewares/fileUpload");

router.route("/send").post(upload.single("profile"), 
((req,res) => {
 *your controller logic here*
});

**Note: Here profile is the name of the file key that you are sending**
bxpogfeg

bxpogfeg7#

使用此选项:

var fileupload = require("express-fileupload");
app.use(fileupload());

相关问题