javascript 使用 FormData 和 multer 上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34091195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:13:33  来源:igfitidea点击:

Uploading a file with FormData and multer

javascriptnode.jsexpressdrag-and-dropmulter

提问by nbro

I have successfully managed to upload a file to a Node server using the multermodule 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 FormDataobject, and send the file using XMLHttpRequest, but it isn't working, the file is always undefinedat the server-side (router).

multer通过使用输入文件对话框选择文件然后提交表单,成功地使用模块将文件上传到节点服务器,但现在我需要创建一个FormData对象,而不是提交表单,然后发送该文件使用XMLHttpRequest,但它不起作用,该文件始终undefined位于服务器端(路由器)。

The function that does the AJAX request is:

执行 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);
  })

}

Note that fileToUploadis defined and the urlis correct, since the correct router method is called. fileToUploadis a Fileobject obtained by dropping a file from the filesystem to a dropzone, and then by accessing the dataTransferproperty of the drop event.

请注意,fileToUpload定义了并且url是正确的,因为调用了正确的路由器方法。fileToUploadFile通过将文件从文件系统dataTransfer拖放到拖放区,然后通过访问拖放事件的属性而获得的对象。

doJSONRequestis a function that creates a XMLHttpRequestobject and sends the file, etc (as explained in the comments).

doJSONRequest是一个创建XMLHttpRequest对象并发送文件等的函数(如注释中所述)。

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);
}

And here's doRequestSetHeaders:

这是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
});

My guess is that multeris not understanding that fileToUploadis 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?

我的猜测是multer不理解这fileToUpload是一个带名称的文件track(不是吗?),即中间件upload.single("track")无法正常工作/解析或什么也没有,或者它根本无法使用FormData,在这种情况下它会一团糟. 继续使用 multer 的替代方案是什么?

How can I upload a file using AJAX and multer?

如何使用 AJAX 和 multer 上传文件?

Don't hesitate to ask if you need more details.

不要犹豫,询问您是否需要更多详细信息。

回答by cviejo

multeruses multipart/form-datacontent-type requests for uploading files. Removing this bit from your doRequestSetHeadersfunction should fix your problem:

multer使用multipart/form-data内容类型请求上传文件。从您的doRequestSetHeaders函数中删除这一点应该可以解决您的问题:

if(method === "POST" || method === "PUT"){
   r.setRequestHeader("Content-Type", "application/json");
}

You don't need to specify the content-typesince FormDataobjects already use the right encoding type. From the docs:

您不需要指定content-type因为FormData对象已经使用了正确的编码类型。从文档

The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data.

如果表单的编码类型设置为 multipart/form-data,则传输的数据与表单的 submit() 方法用于发送数据的格式相同。

Here's a working example. It assumes there's a dropzone with the id drop-zoneand an upload button with an id of upload-button:

这是一个工作示例。它假设有一个带有 id 的 dropzonedrop-zone和一个带有 id的上传按钮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);
}

The server side code is a simple express app with the exact router code you provided.

服务器端代码是一个简单的 express 应用程序,其中包含您提供的确切路由器代码。

回答by Mohamed Abed

to post a FormData object accepted by multer the upload function should be like this

发布一个被multer接受的FormData对象,上传功能应该是这样的

function uploadFile(fileToUpload, url) { 

     var form_data = new FormData();
    //append file here 
    form_data.append('file', fileToUpload, fileToUpload.name);
    //and append the other fields as an object here
       /* var user = {name: 'name from the form',
                      email: 'email from the form' 
                       etc...       
                      }*/
    form_data.append('user', user);

    // 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);
   })

 }