multipart使用NodeJS上传文件 [英] multipart File uploads using NodeJS

查看:1062
本文介绍了multipart使用NodeJS上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < form action =/ file-uploadclass =dropzone dragndropid =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]; //未处理的'错误'事件
^
错误:无效数据
在WriteStream._write(fs.js:1616:31)
onwrite(_stream_writable.js:265: 14)
在WritableState.onwrite(_stream_writable.js:94:5)
在fs.js:1628:5
在Object.wrapper [as oncomplete](fs.js:475: 5)
在process._makeCallback(node.js:321:24)

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

 请求URL:http:// localhost:3000 /文件上传
**请求标头**
接受:application / json
缓存控制:无缓存
内容类型:multipart / form-data; border = ---- WebKitFormBoundaryMmLSkbfQskfIcjfE
原产地:http:// localhost:3000
Pragma:no-cache
引用:http:// localhost:3000 /
用户代理:Mozilla / 5.0(X11; Linux i686)AppleWebKit / 537.17(KHTML,像Gecko)Chrome / 24.0.1312.52 Safari / 537.17
X文件名:截图从2013-03-20 12:23:42。 png
X-Requested-With:XMLHttpRequest
**请求有效负载**
------ WebKitFormBoundaryMmLSkbfQskfIcjfE
内容处理:form-data; NAME = 文件;文件名=2013-03-20截图12:23:42.png
内容类型:image / png


------ WebKitFormBoundaryMmLSkbfQskfIcjfE--

解决方案

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



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



file-upload.js

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

//告诉express使用bodyParser中间件
//并设置上传目录
app.use(express.bodyParser({keepExtensions:true,uploadDir:uploads} ));
app.engine('jade',require('jade').__ express);

app.post(/ upload,function(request,response){
// request.files将包含上传的文件,
//键入输入名称(在这种情况下为文件)

//显示上传的文件名
console.log(file name,request.files.file.name);
console.log(file path,request.files.file.path);

response.end(upload complete);
});

//渲染文件上传表单
app.get(/,function(request,response){
response.render(upload_form.jade);
});

app.listen(3000);

views / upload_form.jade

  doctype 5 
html

标题上传表单
body
h1上传文件
form(method =POST,action =/ upload,enctype =multipart / form-data)
input(type =file,name =file)
input type =submit)


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:

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

Then I have a route in 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:

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

解决方案

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

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:

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:

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

这篇关于multipart使用NodeJS上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆