我是nodejs的新手,想知道如何将文件放入我的系统后端,甚至将其上传到S3等。
以下是文件对象:
req.body { homeColor: 'black',
guestColor: 'white',
thirdColor: 'red',
file:
{ webkitRelativePath: '',
lastModifiedDate: '2014-05-05T02:26:11.000Z',
name: '2014-05-05 10.26.11.jpg',
type: 'image/jpeg',
size: 1310720 },
title: 'tfuyiboinini' }
如何处理req.body.file以便可以物理保存?
请帮助和谢谢!
答案 0 :(得分:1)
长话短说
var fs = require('fs');
app.post('/file-upload', function(req, res) {
var tmp_path = req.files.thumbnail.path;
var target_path = './public/images/' + req.files.thumbnail.name;
fs.rename(tmp_path, target_path, function(err) {
if (err) throw err;
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
});
});
};
你可以在这里阅读更多相关内容: http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html
答案 1 :(得分:0)
首先确保您的POST编码为enctype="multipart/form-data"
....
在Express 4中,您需要在服务器中设置body parser
:
var bodyParser = require('dy-parser');
//...
var app = express();
//...
app.use(bodyParser()); // pull information from html in POST
var busboy = require('connect-busboy');
app.use(busboy());
在早期版本的Express中,您只需要从框架本身添加正文解析器,文件将存储在配置的位置:
app.use(express.bodyParser({limit: '10mb', uploadDir: __dirname + '/public/uploads' })); // pull information from html in POST
由于版本4现在删除了对connect的支持,因此您需要将多部分/表单数据的自定义支持添加到解析器多部分/部分POST,因此您必须执行以下操作:
var fs = require('fs');
var busboy = require('connect-busboy');
//...
app.use(busboy());
//...
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});