最近在用express写自己网站的时候,图片的上传感觉有点小繁琐,做个小笔记,直接上代码
html部分
1 2
| <input type="file" name="file" id="file"/><br/> <button id="upload">Upload</button>
|
js,ajax部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $('#upload').on('click', function(e) { var formData = new FormData(); formData.append('file', $('#file').prop('files')[0]); $.ajax({ url: "/loadPic", contentType: false, processData: false, data: formData, type: 'post', success: function(data) { console.log(data); }, error: function(err) { console.log('error'); } }) });
|
node 部分
我们这里使用 formidable 来弄我们的图片上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| const config = require('../config'); const formidable = require('formidable'); const fs = require('fs');
router.post('/loadPic',(req,res,next) => {
let form = formidable.IncomingForm(); form.encoding = 'utf-8'; form.uploadDir = config.upload.path; form.keepExtensions = true; form.maxFieldsSize = 2 * 1024 * 1024; form.type = true;
form.on('error', function(err) { console.error('upload failed', err.message); next(err); });
form.parse(req,(err, fields, files) => { if (err) { res.send(err); return; }; console.log(files); let extName = ''; switch (files.file.type) { case 'image/pjpeg': extName = 'jpg'; break; case 'image/jpeg': extName = 'jpg'; break; case 'image/png': extName = 'png'; break; case 'image/x-png': extName = 'png'; break; } if (extName.length === 0) { res.json({ code: 202, msg: '只支持png和jpg格式图片' }); return; } else { let avatarName = '/' + Date.now() + '.' + extName; let newPath = form.uploadDir + avatarName; fs.renameSync(files.file.path, newPath); res.json({ success: 1, url: newPath }); } }); });
|
formidable的其他用法可点击查看 https://github.com/felixge/node-formidable