使用 NodeJS 上传多部分文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16534892/
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-09-02 14:29:58  来源:igfitidea点击:

multipart File uploads using NodeJS

node.jsdrag-and-dropmultipartform-datadropzone.js

提问by Matt Hintzke

I am having troubles getting file uploads to work with NodeJS. I am using Dropzone.JS to create a form that sends a POST request to /file-upload here:

我在使用 NodeJS 上传文件时遇到了麻烦。我正在使用 Dropzone.JS 创建一个表单,该表单将 POST 请求发送到 /file-upload 此处:

<form action="/file-upload" class="dropzone dragndrop" id="my-awesome-dropzone"></form> 

Then I have a route in app.js:

然后我在 app.js 中有一个路由:

app.post('/file-upload', routes.upload);

Then my handler:

然后我的处理程序:

exports.upload = function(req, res){
     console.log(req.files);
     res.send("OK");
}

However, the upload function here is never called. The server crashes with this error first:

然而,这里的上传函数从来没有被调用过。服务器首先因此错误而崩溃:

events.js:69
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: Invalid data
    at WriteStream._write (fs.js:1616:31)
    at onwrite (_stream_writable.js:265:14)
    at WritableState.onwrite (_stream_writable.js:94:5)
    at fs.js:1628:5
    at Object.wrapper [as oncomplete] (fs.js:475:5)
    at process._makeCallback (node.js:321:24)

So I am not sure what I should do because it appears that this is not my fault. I followed other tutorials and saw nothing wrong. Also, when I inspect my Network under chrome dev tools, it shows:

所以我不确定我应该做什么,因为这似乎不是我的错。我遵循了其他教程,没有发现任何问题。此外,当我在 chrome 开发工具下检查我的网络时,它显示:

Request URL:http://localhost:3000/file-upload
**Request Headers**
Accept:application/json
Cache-Control:no-cache
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryMmLSkbfQskfIcjfE
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
X-File-Name:Screenshot from 2013-03-20 12:23:42.png
X-Requested-With:XMLHttpRequest
**Request Payload**
------WebKitFormBoundaryMmLSkbfQskfIcjfE
Content-Disposition: form-data; name="file"; filename="Screenshot from 2013-03-20 12:23:42.png"
Content-Type: image/png


------WebKitFormBoundaryMmLSkbfQskfIcjfE--

采纳答案by Robert Mitchell

@user568109 and @nick-fishman are correct; you should use the bodyParser middleware for this.

@user568109 和 @nick-fishman 是正确的;您应该为此使用 bodyParser 中间件。

Please see the sample code for a basic file upload form below. (Note: you will need to create an "uploads" directory to store the files.)

请参阅下面的基本文件上传表单的示例代码。(注意:您需要创建一个“上传”目录来存储文件。)

file-upload.js:

文件上传.js

var express = require("express"),                                                                
    app = express();                                                                             

// tell express to use the bodyParser middleware                                                 
// and set upload directory                                                                      
app.use(express.bodyParser({ keepExtensions: true, uploadDir: "uploads" }));                     
app.engine('jade', require('jade').__express);                                                   

app.post("/upload", function (request, response) {                                               
    // request.files will contain the uploaded file(s),                                          
    // keyed by the input name (in this case, "file")                                            

    // show the uploaded file name                                                               
    console.log("file name", request.files.file.name);                                           
    console.log("file path", request.files.file.path);                                           

    response.end("upload complete");                                                             
});                                                                                              

// render file upload form                                                                       
app.get("/", function (request, response) {                                                      
    response.render("upload_form.jade");                                                         
});                                                                                              

app.listen(3000);

views/upload_form.jade:

意见/upload_form.jade

doctype 5
html
    head
        title Upload Form
    body
        h1 Upload File
        form(method="POST", action="/upload", enctype="multipart/form-data")
            input(type="file", name="file")
            input(type="submit")

回答by Anderson Contreira

Try use busboy-body-parser to retrieve the request body parameters and the files.

尝试使用 busboy-body-parser 来检索请求正文参数和文件。

start.js
var bodyParser = require('body-parser');
var busboyBodyParser = require('busboy-body-parser');


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
}));

// parse application/json
app.use(bodyParser.json());


//parse multipart/form-data    
app.use(busboyBodyParser());



controllers/someController.js
someAction: function(req,res){
     if(req.method == "POST"){
           res.end(JSON.stringify(req.body)+JSON.stringify(req.files));
     }
}
//{"text":"testx"}{"anexo":{"data":{"type":"Buffer","data":.... }}} 
//req.body = {"text":"testx"}
//req.files = {"anexo":{"data":{"type":"Buffer","data":.... }}} 


views/someController/someAction.html
<form method="post" id="multipart" enctype="multipart/form-data">
    <input type="text" id="text1" name="text" value="testx" />
    <input type="file" id="anexo" name="anexo"  />
    <input type="submit" value="Enviar" />
</form>

To create a file uploaded, you need work if the stream, for example:

要创建上传的文件,您需要工作如果流,例如:

/* file props
{  
   "data":{"type":"Buffer","data":.... },
   "fieldname":"anexo",
   "originalname":"images (1).jpg",
   "encoding":"7bit",
   "mimetype":"image/jpeg",
   "destination":"c:\live\sources\uploads\",
   "filename":"eventclock_images(1)_1443706175833.jpg",
   "path":"c:\live\sources\uploads\eventclock_images(1)_1443706175833.jpg",
   "size":9986
}
*/

var fileStream = fs.createWriteStream(file.path);
fileStream.write(file.data);
fileStream.end();

fileStream.on('error', function (err) {
    //console.log("error",err);
});
fileStream.on('finish', function (res) {
    //console.log("finish",res);
});     

回答by Nick Fishman

@user568109 is correct: you need ExpressJS and bodyParser enabled. Do you have a line similar to the following in your configuration?

@user568109 是正确的:您需要启用 ExpressJS 和 bodyParser。您的配置中是否有类似于以下内容的行?

app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' }));