<input type="file" name="image" accept="image/*"> <input type="submit" value="上傳圖片">
使用 FileReader 將本地圖片解析爲base64格式express
使用 FormData 做爲載體將base64圖片數據傳到後臺app
var fileInput = document.getElementsByTagName('input')[0], submitButton = document.getElementsByTagName('input')[1]; var fileReader = new FileReader(), imgData; //獲取本地圖片 fileInput.addEventListaner('change', function(){ var file = fileInput.files[0]; fileReader.readAsDataURL(file); } //將base64格式的圖片數據存到imgData fileReader.addEventListener('onload', function(){ imgData = fileReader.result; } //Ajax上傳圖片數據到後臺 function uploadImg(){ //FormData保存圖片信息 var formData = new FormData(), xhr = new XMLHttpRequest(); formData.append('imgData', imgData); xhr.open('POST', '/uploadImage', true); xhr.send(formData); } submitButton.addEventListener('click', function(){ uploadImg(); }
使用Multipaty解析表單post
var express = require('express'); var router = express.Router(); //引入Multiparty解析表單 var multiparty = require('multiparty'); var fs = require('fs');
router.post('/uploadImage', function(req, res){ var form = new multiparty.Form(); form.parse(req, function(err, fields, files){ //將前臺傳來的base64數據去掉前綴 var imgData = fields.imgData[0].replace(/^data:image\/\w+;base64,/, ''); var dataBuffer = new Buffer(imgData, 'base64'); //寫入文件 fs.writeFile('public/images/imge.png', dataBuffer, function(err){ if(err){ res.send(err); }else{ res.send('保存成功'); } }); }); });