博主经过实践,这里给出两种处理用户上传图片的方法,前后端代码皆有.
1. 前端jQuery,后端Express的Multer中间件
index.html
<!–index.html–><img id="preview" alt="" /><form method="post" enctype="multipart/form-data" action='/update'> <input type="file" name="avatar" onchange="deal()" id='picFile'> <button type="submit">提交</button></form>
fontend.js
function deal(){ let file = new FormData(document.getElementById("picFile")); file.append("CustomField", "This is some extra data"); $.ajax({ url: "/update", type: "POST", data: file, processData: false, / 告诉jQuery不要去处理发送的数据/ contentType: false / 告诉jQuery不要去设置Content-Type请求头/ });}
backend.js
/后端代码:用express初始化项目之后,新建一个路由文件.路由update. update.js /var express = require('express');var router = express.Router();var multer = require('multer');var upload = multer({ dest: 'uploads/' /设置上传的图片/文件存放的地方为根目录下的uploads文件夹/});/single(fieldName) 中的fieldName必须和HTML中input的属性name的值一样/router.post("/",upload.single('avatar'),function(req,res,next) { console.log(req.file); / req.file 是 logo 文件的信息/ console.log(req.body); / req.body 保存表单文本域数据, 如果存在的话/ res.send('Upload Done !');});module.exports = router;
多图片上传
和单图上传并预览基本一个套路.
<!–index.html–><form method="post" enctype="multipart/form-data" action='/update'> <input type="file" name="avatars"> <input type="file" name="avatars"> <input type="file" name="avatars"> <button type="submit">提交</button></form>
/其他地方和上面的一样. update.js/router.post("/",upload.array('avatars',3),function(req,res,next) { console.log(req.files); / req.files 是 avatars 文件数组的信息/ console.log(req.body); / req.body 保存表单文本域数据, 如果存在的话/ res.send('Upload Done !');});
2. 前后端皆原生JS
前端把图片转换成base64格式,后端再转成二进制数据(存成图片)
index.html
<input type='file' ref='files' onchange='inputChange' id='uploadImg'>
fontend.js
inputChange(e) { const files = e.target.files[0]; const reader = new FileReader(); reader.onload = (ee) => { const data = { base64: ee.target.result, }; post(this.uploadUrl, data).then((res) => { // 根据返回数据做些处理. }).catch((err) => { console.info('Error', err); }); }; reader.readAsDataURL(files);}/ 这里把xhr的post给封装了 /post(url, data) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304)) { resolve(JSON.parse(xhr.responseText)); } else { reject(XHR unsuccessful:${xhr.status}); } } }; xhr.open('post', url, true); xhr.setRequestHeader('content-type', 'application/json'); xhr.send(JSON.stringify(data)); });}
backend.js
const express = require('express');const router = express.Router();const fs = require('fs');router.route('/') .post(upload.single('image'), (req, res) => { let base64 = req.body.base64; //去掉base64数据最前面的"图片类型"字符串 let type = base64.match(/^data:image\/(.+);/)[1]; base64 = base64.replace(/^data:image\/\w+;base64,/, ""); // 解码base64成二进制数据. let data = new Buffer(base64, 'base64'); const name = uploads/images/${String(new Date()).replace(/[ :]/g,'').match(/.{6}(.{12})/)[1]}.${type}; fs.open(name, "a", 0644, function(e, fd) { if (e) throw e; fs.write(fd, data, function(e) { if (e) throw e; fs.closeSync(fd); res.json({ 'path': name.replace('uploads', ''), }); }); }); });module.exports = router;
PS: 关于美化文件上传按钮,一个思路就是设置input的opacity为0,然后在外面包裹一个div.