我在node.js中上传文件时遇到问题。不使用快递。并且大多数在线示例都是使用expres。上传文件的。
将不胜感激任何指针。
function fileUploader2(req, res, next) {
var busboy = new Busboy({ headers: req.headers });
req.pipe(busboy);
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
// var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
file.pipe(fs.createWriteStream('./upload/' + filename));
});
busboy.on('finish', function() {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
res.end();
};
以上不起作用。再次,我不使用快递。将不胜感激。
最佳答案
在这里,我为您举例。它为我工作。
const Busboy = require('busboy');
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
var busboy = new Busboy({
headers: req.headers
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
saveTo = `${__dirname}/${filename}`;
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
res.writeHead(200, {
'Connection': 'close'
});
res.end("That's all folks!");
});
return req.pipe(busboy);
res.writeHead(404);
res.end();
});
server.listen(8000, function() {
console.log('magic at 8000');
});