我尝试使用快递上传文件但我在请求数据事件上遇到问题。 即使我对其进行了一些控制台记录测试,数据事件也不起作用。
这是我的服务器代码:
var express = require('express');
var fs = require('fs');
var app = express();
//parser
app.use(express.bodyParser());
//form
app.get('/', function (req, res){
res.sendfile(__dirname + "/upload.html");
});
//post
app.post('/', function(req, res){
var imageName = req.files.image.name;
//error
if(!imageName){
console.log("Error");
res.redirect("/");
res.end();
} else {
var file = fs.createWriteStream(__dirname + "/uploads/" + imageName);
var fileSize = req.headers['content-length'];
var uploadedSize = 0;
req.on('data', function (chunk) {
var bufferStore = file.write(chunk);
if(bufferStore == false)
req.pause();
uploadedSize += chunk.length;
uploadProgress = (uploadedSize/fileSize) * 100;
console.log(Math.round(uploadProgress) + "%" + " uploaded\n" );
});
file.on('drain', function() {
req.resume();
});
req.on('end', function() {
console.log('Upload done!');
res.end();
});
}
});
app.listen(5000);
这是我的客户代码:
<!DOCTYPE HTML>
<html>
<body>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='image'/>
<input type='submit' /></form>
</body>
</html>
答案 0 :(得分:0)
添加此模块:
var path = require('path');
然后,尝试用以下内容替换你的帖子:
app.post('/', function(req, res) {
var uploadDir = __dirname + '/uploads/';
if( !path.existsSync(uploadDir) ){
fs.mkdirSync(uploadDir, 0755);
}
var filename = req.files.image.name;
fs.readFile(req.files.image.path, function (err, data) {
var save_path = uploadDir + filename;
fs.writeFile(save_path, data, function (err) {
if(err){
res.json({
error: 'Error!'
});
} else {
res.json({
success: true
});
}
fs.unlink(req.files.image.path, function (err) {
if (err) throw err;
});
});
});
});