multipart使用NodeJS上传文件

时间:2013-05-14 04:02:33

标签: node.js drag-and-drop multipartform-data dropzone.js

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

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

然后我在app.js中有一条路线:

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

然后是我的经纪人:

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

但是,此处的上传功能永远不会被调用。服务器首先崩溃:

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)

所以我不确定自己该做什么,因为看来这不是我的错。我遵循其他教程,没有看错。此外,当我在chrome dev工具下检查我的网络时,它会显示:

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--

3 个答案:

答案 0 :(得分:11)

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

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

文件-upload.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);

<强>视图/ 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")

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

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

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

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

C: