2013-06-20 40 views
7

Tôi đang cố gắng tải tệp lên máy chủ js nút của tôi bằng cách sử dụng express. Đây là mã nodejs tôi:Tải tệp lên máy chủ Node JS

var express=require('express'); 
var app=express(); 
var fs=require('fs'); 
var sys=require('sys'); 
app.listen(8080); 
app.get('/',function(req,res){ 
fs.readFile('upload.html',function (err, data){ 
    res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length}); 
    res.write(data); 
    res.end(); 
}); 



}); 
app.post('/upload',function(req,res) 
{ 
console.log(req.files); 
fs.readFile(req.files.displayImage.path, function (err, data) { 
    // ... 
    var newPath = __dirname; 
    fs.writeFile(newPath, data, function (err) { 
    res.redirect("back"); 
    }); 
}); 

}); 

upload.html My file:

<html> 
<head> 
<title>Upload Example</title> 
</head> 
<body> 

<form id="uploadForm" 
     enctype="multipart/form-data" 
     action="/upload" 
     method="post"> 
    <input type="file" id="userPhotoInput" name="displayImage" /> 
    <input type="submit" value="Submit"> 
</form> 

<span id="status" /> 
<img id="uploadedImage" /> 


</body> 
</html> 

Tôi nhận được một lỗi mà các req.files là undefined. Điều gì có thể sai? Tải lên tệp cũng không hoạt động.

Trả lời

10

Như đã nêu trong the docs, req.files, cùng với req.body được cung cấp bởi phần mềm trung gian bodyParser. Bạn có thể thêm phần mềm trung gian như thế này:

app.use(express.bodyParser()); 

// or, as `req.files` is only provided by the multipart middleware, you could 
// add just that if you're not concerned with parsing non-multipart uploads, 
// like: 
app.use(express.multipart()); 
+0

Cảm ơn rất nhiều. Tôi không nên bỏ lỡ điều đó. –

Các vấn đề liên quan