Node.js之图片上传
本文用node进行图片上传主要借助formidable插件,具体使用步骤如下:
1、安装formidable插件
npm install formidable -D
2、引入依赖包
const formidable = require('formidable');
3、接口实现逻辑
1 router.post('/uploadFile', (req, res, next) => { 2 let form = new formidable.IncomingForm(); 3 form.encoding = 'utf-8'; 4 //上传到服务器指定文件夹 5 form.uploadDir =`public/${constant.UPLOAD_FOLDER}`; 6 form.keepExtensions = true; //保留后缀 7 form.maxFieldsSize = constant.IMAGE_SIZE; 8 let data = new MsgBean('上传失败',1); 9 form.parse(req, (err, fields, files) => { 10 if (err) { 11 data.setContent(err); 12 res.send(data); 13 return; 14 } 15 let file = files.file; 16 let fileType = new RegExp(file.type, 'g'); 17 18 let isLegal = fileType.test(constant.IMAGE_TYPE); 19 if(!isLegal) {//判断上传图片格式是否合法 20 data.msg('非法的图片格式'); 21 res.send(data); 22 return; 23 } 24 let fileSize = file.size; 25 if(fileSize > constant.IMAGE_SIZE) {//上传图片超出最大限度 26 data.msg('图片大小超出最大限制'); 27 res.send(data); 28 return; 29 } 30 let index = file.name.lastIndexOf('.'); 31 let oldPath = files.file.path; 32 let uploadDate = new Date().getTime(); 33 let fileName = `${file.name.slice(0, index)}_${uploadDate}_origin.${file.name.slice(index+1)}`; 34 let newPath = `public/${constant.UPLOAD_FOLDER}/${fileName}`; 35 fs.rename(oldPath, newPath, err => {//图片更名 36 if(err) { 37 data.setContent('图片解析失败'); 38 res.send(data); 39 return; 40 } 41 let baseUrl = req.headers.host; 42 let imgUrl = `http://${baseUrl}/${constant.UPLOAD_FOLDER}/${fileName}`; 43 let result = { 44 imgUrl 45 }; 46 data.setCode(0); 47 data.setContent(result); 48 data.setMsg('上传成功'); 49 res.send(data); 50 }); 51 }) 52 });
本文为原创文章,如有转载,烦请注明出处,谢谢!