gpt4 book ai didi

javascript - req.file 未定义(multer,node.js)

转载 作者:行者123 更新时间:2023-11-30 20:57:52 25 4
gpt4 key购买 nike

一段时间以来,我一直在尝试上传图片,但 req.file 仍未定义。有人能看出原因吗?

this is my page. I am able to pick an image when I click the '+' glyphicon, but on the server side req.file is still empty.

EJS 文件

input[type="file"] 和 input[type="submit"] 有 css 样式 display: none

<form action="/profile/addProfilepicture" method="post" id="form" enctype="multipart/form-data">
<span id="upload" class="glyphicon glyphicon-plus-sign"></span>
<label for="profilePic"></label>
<input id=profilePic type='file' />
<input type="submit">
</form>

<img class="profileImg"
src="<%="images/pexels-photo-370799.jpeg"%>"
alt="fail">

客户端 JS 文件

当我点击“+”符号时,它会让我选择一张图片。当我这样做时,这将触发表单提交并发送发布请求。

   $("#upload").on('click',function() {
$("input[type='file']").click();
});

$('input[type="file"]').change(function (e) {
$("input[type='submit']").click()
});

服务器端 JS

在服务器端它停止在:

TypeError: Cannot read property 'filename' of undefined at C:\Users\Tijl Declerck\Desktop\projects\digitalNomadApp\routes\profile.js:27:38 at Immediate._onImmediate (C:\Users\Tijl Declerck\Desktop\projects\digitalNomadApp\node_modules\multer\lib\make-middleware.js:53:37) at runCallback (timers.js:793:20) at tryOnImmediate (timers.js:751:5) at processImmediate [as _immediateCallback] (timers.js:722:5)

我尝试的 console.logs 给了我这个:req.body 返回一个空对象,req.file 返回 undefined。

var express = require('express');
var router = express.Router();
var multer = require('multer');
var User = require('../models/Users');

var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/profilePics')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});

var upload = multer({ storage: storage }).single('myImage');


router.post('/addProfilePicture', function (req, res) {

var profilePicUrl = '';
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading

} else {
console.log(req.file);
profilePicUrl = req.file.filename;

User.update({username: req.user.username}, {'profilePic.uploaded': true, 'profilePic.link': profilePicUrl}, function(err, doc){
console.log('THIS IS DONE')
});
}
});
});

最佳答案

您必须为您的文件输入提供一个名称,它应该与单个方法的名称相匹配,这来自 multer 文档:

.single(fieldname)

Accept a single file with the name fieldname. The single file will be stored in req.file.

这没有很好的记录,但 fieldname 指的是输入名称属性

EJS 文件

<input id='profilePic' name='myImage' type='file'  />

express

...
var upload = multer({ storage: storage }).single('myImage');
...

关于javascript - req.file 未定义(multer,node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com