图片上传是web开发中经常用到的功能,node社区在这方面也有了相对完善的支持。
常用的开源组件有multer、formidable等,借助这两个开源组件,可以轻松搞定图片上传。
本文主要讲解以下内容,后续章节会对技术实现细节进行深入挖掘。本文所有例子均有代码示例,可在这里查看。
非常简单,一行命令。
npm install express multer multer --save
➜ upload-custom-filename git:(master) ✗ tree -L 1
.
├── app.js # 服务端代码,用来处理文件上传请求
├── form.html # 前端页面,用来上传文件
var fs = require('fs');
var express = require('express');
var multer = require('multer')
var app = express();
var upload = multer({ dest: 'upload/' });
// 单图上传
app.post('/upload', upload.single('logo'), function(req, res, next){
res.send({ret_code: '0'});
});
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);
html
多图上传
var fs = require('fs');
var express = require('express');
var multer = require('multer')
var app = express();
var upload = multer({ dest: 'upload/' });
// 多图上传
app.post('/upload', upload.array('logo', 2), function(req, res, next){
res.send({ret_code: '0'});
});
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);
var fs = require('fs');
var express = require('express');
var multer = require('multer')
var app = express();
var upload = multer({ dest: 'upload/' });
// 单图上传
app.post('/upload', upload.single('logo'), function(req, res, next){
var file = req.file;
console.log('文件类型:%s', file.mimetype);
console.log('原始文件名:%s', file.originalname);
console.log('文件大小:%s', file.size);
console.log('文件保存路径:%s', file.path);
res.send({ret_code: '0'});
});
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);
启动服务,上传文件后,就会看到控制台下打印出的信息
文件类型:image/png
原始文件名:1.png
文件大小:18379
文件保存路径:upload/b7e4bb22375695d92689e45b551873d9
var fs = require('fs');
var express = require('express');
var multer = require('multer')
var app = express();
var createFolder = function(folder){
try{
fs.accessSync(folder);
}catch(e){
fs.mkdirSync(folder);
}
};
var uploadFolder = './upload/';
createFolder(uploadFolder);
// 通过 filename 属性定制
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadFolder); // 保存的路径,备注:需要自己创建
},
filename: function (req, file, cb) {
// 将保存文件名设置为 字段名 + 时间戳,比如 logo-1478521468943
cb(null, file.fieldname + '-' + Date.now());
}
});
// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })
// 单图上传
app.post('/upload', upload.single('logo'), function(req, res, next){
var file = req.file;
res.send({ret_code: '0'});
});
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);
form.html。
multer官方文档:https://github.com/expressjs/multer
https://www.cnblogs.com/chyingp/p/express-multer-file-upload.html