问题描述
我已成功地使用 multer
模块将文件上传到Node服务器,方法是使用输入文件对话框选择文件,然后提交表单,但现在我需要,而不是提交表单来创建一个 FormData
对象,并使用 XMLHttpRequest
发送文件,但是它不起作用,文件始终是 undefined
在服务器端(路由器)。
I have successfully managed to upload a file to a Node server using the multer
module by selecting the file using the input file dialog and then by submitting the form, but now I would need, instead of submitting the form, to create a FormData
object, and send the file using XMLHttpRequest
, but it isn't working, the file is always undefined
at the server-side (router).
功能AJAX请求是:
function uploadFile(fileToUpload, url) {
var form_data = new FormData();
form_data.append('track', fileToUpload, fileToUpload.name);
// This function simply creates an XMLHttpRequest object
// Opens the connection and sends form_data
doJSONRequest("POST", "/tracks/upload", null, form_data, function(d) {
console.log(d);
})
}
请注意, fileToUpload
被定义, url
是正确的,因为正确路由器方法被调用。 fileToUpload
是一个文件
对象,将文件从文件系统中删除到一个dropzone,然后访问<$删除事件的c $ c> dataTransfer 属性。
Note that fileToUpload
is defined and the url
is correct, since the correct router method is called. fileToUpload
is a File
object obtained by dropping a file from the filesystem to a dropzone, and then by accessing the dataTransfer
property of the drop event.
doJSONRequest
是一个创建 XMLHttpRequest
对象的函数并发送文件等(如评论中所述)。
doJSONRequest
is a function that creates a XMLHttpRequest
object and sends the file, etc (as explained in the comments).
function doJSONRequest(method, url, headers, data, callback){
//all the arguments are mandatory
if(arguments.length != 5) {
throw new Error('Illegal argument count');
}
doRequestChecks(method, true, data);
//create an ajax request
var r = new XMLHttpRequest();
//open a connection to the server using method on the url API
r.open(method, url, true);
//set the headers
doRequestSetHeaders(r, method, headers);
//wait for the response from the server
r.onreadystatechange = function () {
//correctly handle the errors based on the HTTP status returned by the called API
if (r.readyState != 4 || (r.status != 200 && r.status != 201 && r.status != 204)){
return;
} else {
if(isJSON(r.responseText))
callback(JSON.parse(r.responseText));
else if (callback !== null)
callback();
}
};
//set the data
var dataToSend = null;
if (!("undefined" == typeof data)
&& !(data === null))
dataToSend = JSON.stringify(data);
//console.log(dataToSend)
//send the request to the server
r.send(dataToSend);
}
这里是 doRequestSetHeaders
:
function doRequestSetHeaders(r, method, headers){
//set the default JSON header according to the method parameter
r.setRequestHeader("Accept", "application/json");
if(method === "POST" || method === "PUT"){
r.setRequestHeader("Content-Type", "application/json");
}
//set the additional headers
if (!("undefined" == typeof headers)
&& !(headers === null)){
for(header in headers){
//console.log("Set: " + header + ': '+ headers[header]);
r.setRequestHeader(header, headers[header]);
}
}
}
和我的路由器上传文件如下
and my router to upload files is the as follows
// Code to manage upload of tracks
var multer = require('multer');
var uploadFolder = path.resolve(__dirname, "../../public/tracks_folder");
function validTrackFormat(trackMimeType) {
// we could possibly accept other mimetypes...
var mimetypes = ["audio/mp3"];
return mimetypes.indexOf(trackMimeType) > -1;
}
function trackFileFilter(req, file, cb) {
cb(null, validTrackFormat(file.mimetype));
}
var trackStorage = multer.diskStorage({
// used to determine within which folder the uploaded files should be stored.
destination: function(req, file, callback) {
callback(null, uploadFolder);
},
filename: function(req, file, callback) {
// req.body.name should contain the name of track
callback(null, file.originalname);
}
});
var upload = multer({
storage: trackStorage,
fileFilter: trackFileFilter
});
router.post('/upload', upload.single("track"), function(req, res) {
console.log("Uploaded file: ", req.file); // Now it gives me undefined using Ajax!
res.redirect("/"); // or /#trackuploader
});
我的猜测是, multer
不了解 fileToUpload
是名为 track
的文件(不是吗?),即中间件 upload.single(track)
没有正常工作/解析,或者根本就不适用于 FormData
情况会是一团糟
My guess is that multer
is not understanding that fileToUpload
is a file with name track
(isn't it?), i.e. the middleware upload.single("track")
is not working/parsing properly or nothing, or maybe it simply does not work with FormData
, in that case it would be a mess. What would be the alternatives by keeping using multer?
如何使用AJAX和multer上传文件?
How can I upload a file using AJAX and multer?
请不要犹豫,问你是否需要更多的细节。
Don't hesitate to ask if you need more details.
推荐答案
使用 multipart / form-data
上传文件的内容类型请求。从 doRequestSetHeaders
函数中删除该位可以解决您的问题:
multer uses multipart/form-data
content-type requests for uploading files. Removing this bit from your doRequestSetHeaders
function should fix your problem:
if(method === "POST" || method === "PUT"){
r.setRequestHeader("Content-Type", "application/json");
}
您不需要指定 content-键入
,因为 FormData
对象已经使用正确的编码类型。从:
You don't need to specify the content-type
since FormData
objects already use the right encoding type. From the docs:
这是一个工作示例。它假定有一个名为 drop-zone
的dropzone,上传按钮的ID为 upload-button
:
Here's a working example. It assumes there's a dropzone with the id drop-zone
and an upload button with an id of upload-button
:
var dropArea = document.getElementById("drop-zone");
var uploadBtn = document.getElementById("upload-button");
var files = [];
uploadBtn.disabled = true;
uploadBtn.addEventListener("click", onUploadClick, false);
dropArea.addEventListener("dragenter", prevent, false);
dropArea.addEventListener("dragover", prevent, false);
dropArea.addEventListener("drop", onFilesDropped, false);
//----------------------------------------------------
function prevent(e){
e.stopPropagation();
e.preventDefault();
}
//----------------------------------------------------
function onFilesDropped(e){
prevent(e);
files = e.dataTransfer.files;
if (files.length){
uploadBtn.disabled = false;
}
}
//----------------------------------------------------
function onUploadClick(e){
if (files.length){
sendFile(files[0]);
}
}
//----------------------------------------------------
function sendFile(file){
var formData = new FormData();
var xhr = new XMLHttpRequest();
formData.append("track", file, file.name);
xhr.open("POST", "http://localhost:3000/tracks/upload", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.send(formData);
}
服务器端代码是一个简单的Express应用程序,其中提供了确切的路由器代码。
The server side code is a simple express app with the exact router code you provided.
这篇关于使用FormData和multer上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!