我试图从浏览器中上传一个图片(jpg/jpeg/png)到NodeJS。我在论坛上读过几篇教程和许多帖子,但似乎很少有这个具体的问题。
我已经确保将提供给穆特( (formData.append('upload', selectedFile, selectedFile.name)
)
upload.single('upload')
)匹配,但后来读到应该排除它们。
<form action="/upload" method="post" enctype="multipart/form-data">
提交,但仍然得到相同的错误。我发现这个类似的问题,只有一个答案是不清楚的,Multer gives unexpetcted end of form error和Unexpected end of form at Multipart._final,没有答案。所有其他问题似乎都是关于“意外字段”或“多部分数据的意外结束”错误,从解决方案来看,这个错误在这里是无关紧要的。
下面是我的密码..。
浏览器:
<body>
<input type="file" id="file_uploader" name="upload" />
<button onclick="uploadImage()" class="btn-default">SUBMIT</button>
<!-- OTHER STUFF -->
</body>
<script>
let selectedFile;
let uploadData = new FormData();
const fileInput = document.getElementById('file_uploader');
fileInput.onchange = () => {
selectedFile = fileInput.files[0];
uploadData.append('upload', selectedFile, selectedFile.name);
}
function uploadImage(){
fetch('/upload', {
method: 'POST',
body: uploadData
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error('Error: ', error);
});
}
</script>
NodeJS
let express = require('express');
const multer = require('multer');
//multer options
const upload = multer({
dest: './upload/',
limits: {
fileSize: 1000000,
}
})
const app = express();
app.post('/upload', upload.single('upload'), (req, res) => {
res.send();
}, (error, req, res, next) => {
console.log(error.message);
})
exports.app = functions.https.onRequest(app);
...And这里是错误日志,如果它有帮助的话:
Error: Unexpected end of form
> at Multipart._final (C:\Users\p\Downloads\MyInvestmentHub\functions\node_modules\busboy\lib\types\multipart.js:588:17)
> at callFinal (node:internal/streams/writable:694:27)
> at prefinish (node:internal/streams/writable:723:7)
> at finishMaybe (node:internal/streams/writable:733:5)
> at Multipart.Writable.end (node:internal/streams/writable:631:5)
> at onend (node:internal/streams/readable:693:10)
> at processTicksAndRejections (node:internal/process/task_queues:78:11)
到目前为止,我还没有贴出很多问题,所以如果我遗漏了什么或者格式被取消了,我很抱歉。让我知道,我会做适当的编辑。
谢谢。
发布于 2022-08-03 09:40:08
我也得到了完全相同的错误。
在使用穆特之前,我已经安装了express-fileupload
。当我使用命令npm uninstall express-fileupload
使其脱离状态时,我可以消除错误。
如果情况与此相同,请不要忘记删除已经为express-fileupload
模块添加的命令。(如要求丝状体)
发布于 2022-06-13 12:01:48
嗨,我遇到了同样的问题,那就是缺少一个bodyParser
中间件,可以将我们的请求文件解析成Buffers
。
我以这样的方式解决了这个问题:
var bodyParser = require('body-parser')
bodyParser.json([options])
发布于 2022-09-04 14:03:09
在我的例子中,原因是其他中间件。检查在multer之前运行的其他中间件。对我来说,问题在于快速开放验证器中间件。一旦我删除了那个中间件,它就像预期的那样工作了。
https://stackoverflow.com/questions/72544409
复制相似问题