请考虑更新的答案,这些答案包含多年来发生变化的最新信息!
由于许多新的Node.js库很快就被淘汰了,而且我想要询问有关使用以下内容上传图像的例子相对较少:
其他人是如何做到的?
我找到了node-formidable,但我不熟悉上传图片,所以我想学习使用Node.js和Express的一般内容和方法。
答案 0 :(得分:75)
我第一次回答我自己的问题。我直接从源头找到了一个例子。请原谅可怜的缩进。复制和粘贴时我不确定如何正确缩进。该代码直接来自GitHub上的Express multipart/form-data
example。
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
答案 1 :(得分:47)
由于你正在使用express,只需添加bodyParser:
app.use(express.bodyParser());
然后您的路线将自动访问req.files中的上传文件:
app.post('/todo/create', function (req, res) {
// TODO: move and rename the file using req.files.path & .name)
res.send(console.dir(req.files)); // DEBUG: display available fields
});
如果您将输入控件命名为“todo”(在Jade中):
form(action="/todo/create", method="POST", enctype="multipart/form-data")
input(type='file', name='todo')
button(type='submit') New
当你在'files.todo'中获得路径和原始文件名时,上传的文件就准备好了:
其他有用的req.files属性:
答案 2 :(得分:19)
您可以在主应用程序文件的配置块中配置连接主体解析器中间件:
/** Form Handling */
app.use(express.bodyParser({
uploadDir: '/tmp/uploads',
keepExtensions: true
}))
app.use(express.limit('5mb'));
答案 3 :(得分:14)
请注意,您可以做的最好的事情就是将图像上传到磁盘并将URL保存在MongoDB中。再次检索图像时休息。只需指定URL,即可获得图像。上传代码如下。
app.post('/upload', function(req, res) {
// Get the temporary location of the file
var tmp_path = req.files.thumbnail.path;
// Set where the file should actually exists - in this case it is in the "images" directory.
target_path = '/tmp/' + req.files.thumbnail.name;
// Move the file from the temporary location to the intended location
fs.rename(tmp_path, target_path, function(err) {
if (err)
throw err;
// Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
fs.unlink(tmp_path, function() {
if (err)
throw err;
//
});
});
});
现在将目标路径保存在MongoDB数据库中。
同样,在检索图像时,只需从MongoDB数据库中提取URL,然后在此方法中使用它。
fs.readFile(target_path, "binary", function(error, file) {
if(error) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.write(error + "\n");
res.end();
}
else {
res.writeHead(200, {"Content-Type": "image/png"});
res.write(file, "binary");
}
});
答案 4 :(得分:9)
试试这个代码。它会有所帮助。
app.get('/photos/new', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Data: <input type="filename" name="filename" /></p>'
+ '<p>file: <input type="file" name="file" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/photos/new', function(req, res) {
req.form.complete(function(err, fields, files) {
if(err) {
next(err);
} else {
ins = fs.createReadStream(files.photo.path);
ous = fs.createWriteStream(__dirname + '/directory were u want to store image/' + files.photo.filename);
util.pump(ins, ous, function(err) {
if(err) {
next(err);
} else {
res.redirect('/photos');
}
});
//console.log('\nUploaded %s to %s', files.photo.filename, files.photo.path);
//res.send('Uploaded ' + files.photo.filename + ' to ' + files.photo.path);
}
});
});
if (!module.parent) {
app.listen(8000);
console.log("Express server listening on port %d, log on to http://127.0.0.1:8000", app.address().port);
}
答案 5 :(得分:8)
您还可以使用以下方法设置保存文件的路径。
req.form.uploadDir = "<path>";
答案 6 :(得分:5)
我created an example使用Express和Multer。它非常简单,可以避免所有 Connect 警告
这可能对某人有帮助。
答案 7 :(得分:2)
对于Express 3.0,如果要使用强大的事件,则必须删除多部分中间件,以便创建它的新实例。
要做到这一点:
app.use(express.bodyParser());
可以写成:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); // Remove this line
现在创建表单对象:
exports.upload = function(req, res) {
var form = new formidable.IncomingForm;
form.keepExtensions = true;
form.uploadDir = 'tmp/';
form.parse(req, function(err, fields, files){
if (err) return res.end('You found error');
// Do something with files.image etc
console.log(files.image);
});
form.on('progress', function(bytesReceived, bytesExpected) {
console.log(bytesReceived + ' ' + bytesExpected);
});
form.on('error', function(err) {
res.writeHead(400, {'content-type': 'text/plain'}); // 400: Bad Request
res.end('error:\n\n'+util.inspect(err));
});
res.end('Done');
return;
};
我也在我的博客 Getting formidable form object in Express 3.0 on upload 上发布了此内容。
答案 8 :(得分:2)
如果您不想使用bodyParser,则以下工作原理如下:
var express = require('express');
var http = require('http');
var app = express();
app.use(express.static('./public'));
app.configure(function(){
app.use(express.methodOverride());
app.use(express.multipart({
uploadDir: './uploads',
keepExtensions: true
}));
});
app.use(app.router);
app.get('/upload', function(req, res){
// Render page with upload form
res.render('upload');
});
app.post('/upload', function(req, res){
// Returns json of uploaded file
res.json(req.files);
});
http.createServer(app).listen(3000, function() {
console.log('App started');
});
答案 9 :(得分:1)
我知道原来的问题与特定版本有关,但它也提到了“最新” - @JohnAllen的帖子由于Expressjs bodyParser and connect-form
而不再相关这演示了易于使用的内置bodyParser():
/**
* Module dependencies.
*/
var express = require('express')
var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/home/svn/rest-api/uploaded' }))
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
res.send('Uploaded: ' + req.files.image.name)
return next()
});
app.listen(3000);
console.log('Express app started on port 3000');
答案 10 :(得分:0)
这是一种使用强大的程序包上传图像的方法,在Express的更高版本中推荐使用bodyParser。这还包括动态调整图像大小的功能:
从我的网站:Uploading and Resizing Images (on the fly) With Node.js and Express。
这是要点:
var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs = require('fs-extra'),
qt = require('quickthumb');
// Use quickthumb
app.use(qt.static(__dirname + '/'));
app.post('/upload', function (req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
form.on('end', function(fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Location where we want to copy the uploaded file */
var new_location = 'uploads/';
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.error(err);
} else {
console.log("success!")
}
});
});
});
// Show the upload form
app.get('/', function (req, res){
res.writeHead(200, {'Content-Type': 'text/html' });
/* Display the file upload form. */
form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
'+ '<input multiple="multiple" name="upload" type="file" />
'+ '<input type="submit" value="Upload" />'+ '</form>';
res.end(form);
});
app.listen(8080);
注意:这需要使用Image Magick快速调整大小。
答案 11 :(得分:0)
我的方法是多个上传文件:
Nodejs:
router.post('/upload', function(req , res) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');
form.parse(req, function(err, fields, files) {
var imgArray = files.imatges;
for (var i = 0; i < imgArray.length; i++) {
var newPath = './public/uploads/'+fields.imgName+'/';
var singleImg = imgArray[i];
newPath+= singleImg.originalFilename;
readAndWriteFile(singleImg, newPath);
}
res.send("File uploaded to: " + newPath);
});
function readAndWriteFile(singleImg, newPath) {
fs.readFile(singleImg.path , function(err,data) {
fs.writeFile(newPath,data, function(err) {
if (err) console.log('ERRRRRR!! :'+err);
console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
})
})
}
})
确保您的表单包含enctype =&#34; multipart / form-data&#34;
我希望这能帮到你;)
答案 12 :(得分:0)
在将字符串转换为字符串后,只需在前端将图像中的字符串转换为文件即可轻松存储文件
使用您的api中的此代码将图像转换为base64字符串,也不要忘记从上传文件夹中删除文件
"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")
删除文件
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
fs.unlink(req.file.path, resultHandler);
在您的路线上输入multer
`multer const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`
Add upload.single('img') in your request
router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]),
upload.single('img'), usersController.fellowsdetails);
OR
如果您想将图像保存在localstorage
中并想在数据库中保存路径,可以尝试以下方法
您必须首先安装fs-extra,它将创建文件夹。我正在按ID创建单独的文件夹,如果要删除它,可以将其删除。和 要保存上传图片的路径,请将此代码添加到您用于保存图片的api或控制器中,并将其与其他数据一起添加到数据库中
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
为multer
创建一个单独的文件夹,例如multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
在您的路线中导入multerhelper
文件
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper. createUserImage , function(req, res, next) {
//Here accessing the body datas.
})