这篇文章给大家介绍使用node和multer怎么实现一个图片上传功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
const express = require('express');
const path = require('path');
const multer = require('multer');
const app = new express();
// 设置静态目录 第一个参数为虚拟的文件前缀,实际上文件系统中不存在
// 可以用public做为前缀来加载static文件夹下的文件了
app.use('/public', express.static(path.join(__dirname, './static')));
// 根据当前文件目录指定文件夹
const dir = path.resolve(__dirname, '../static/img');
// 图片大小限制KB
const SIZELIMIT = 500000;
const storage = multer.diskStorage({
// 指定文件路径
destination: function(req, file, cb) {
// !!!相对路径时以node执行目录为基准,避免权限问题,该目录最好已存在*
// cb(null, './uploads');
cb(null, dir);
},
// 指定文件名
filename: function(req, file, cb) {
// filedname指向参数key值
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({
storage: storage
});
app.post('/upload', upload.single('file'), (req, res) => {
// 即将上传图片的key值 form-data对象{key: value}
// 检查是否有文件待上传
if (req.file === undefined) {
return res.send({
errno: -1,
msg: 'no file'
});
}
const {size, mimetype, filename} = req.file;
const types = ['jpg', 'jpeg', 'png', 'gif'];
const tmpTypes = mimetype.split('/')[1];
// 检查文件大小
if (size >= SIZELIMIT) {
return res.send({
errno: -1,
msg: 'file is too large'
});
}
// 检查文件类型
else if (types.indexOf(tmpTypes) < 0) {
return res.send({
errno: -1,
msg: 'not accepted filetype'
});
}
// 路径可根据设置的静态目录指定
const url = '/public/img/' + filename;
res.json({
errno: 0,
msg: 'upload success',
url
});
});
app.listen(3000, () => {
console.log('service start');
});
关于使用node和multer怎么实现一个图片上传功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。