节点js multer文件上传不起作用。 req.file和req.files总是未定义的 [英] node js multer file upload not working. req.file and req.files always undefined
问题描述
我正在尝试将文件上传到我的服务器,但是 req.file
和 req.files
总是在我的POST REST端点上未定义。
I am trying to upload a file to my server, but req.file
and req.files
is always undefined on my POST REST endpoint.
我试图上传的内容是一个.dat文件,我期待一个json响应。
The content I'm trying to upload is a ".dat" file, and I am expecting a json response.
这是我的代码:
服务器端:
var express = require('express');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/creoUpload', upload.single('uploadFileField'), function(req, res, next) {
console.log("req.file = ",JSON.stringify(req.file)); //is undefined
console.log("req.files = ",JSON.stringify(req.files)); //also undefined
});
客户端:
<form id="creoUploadForm" action="/creoUpload" enctype="multipart/form-data" method="post">
<input type='file' name='uploadFileField'><br><br>
<input type='submit' value='Upload'/>
</form>
JS:
$( "#creoUploadForm" ).submit(function( event ) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '/creoUpload',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
console.log("RETURN DATA IS: ",returndata);
},
error: function (err) {
console.log("ERROR: ",err);
}
});
});
我一直在玩这些字段,但它不起作用..有人看到我做错了什么在这里?
I keep playing around with the fields but it's not working.. anyone see what I'm doing wrong here?
我正在关注中的示例https://www.npmjs.com/package/multer
版本:
Versions:
- 快递版本:4.12.0
- 节点版本:6.5.0
- JQuery:1.12.1
谢谢!
推荐答案
您正在使用multer作为中间件,因此在进入您的功能并打印之前,它已将图像上传到存储并从 req.files 中删除记录。
You are using multer as a middleware, So before entering into your function and printing it has uploaded images to storage and removes record from req.files.
有两种方法可以访问req.files。
There are two ways you can access req.files.
-
使用multer作为 finw3 所述的函数。
另一个解决方案是:
//代码开始
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/filepath')
},
filename: function (req, file, cb) {
let filename = 'filenametogive';
req.body.file = filename
cb(null, filename)
}
})
var upload = multer({ storage: storage })
//代码结束
现在您可以访问req.body.file
Now you can access files in req.body.file
这篇关于节点js multer文件上传不起作用。 req.file和req.files总是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!