小菜鸟一枚,朋友问到图片上传,就写了个小demo,不多说,祭上主要代码
<input type="file" id="img_upload_file" />
<label>图片预览</label> <img id="img_upload_show" />
$("#img_upload_file").change(function() { var file = this.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function() { getdata(this.result) $("#img_upload_show").attr("src", this.result); }; }); function getdata(imgData) { $.ajax({ url:'http://localhost:3000/load', type:'post', data:{ imgData:imgData }, success:function (res) { console.log(res.info); }, error:function (res) { console.log(res.info); } }) }
后台使用node的express框架,简单明了
app.post('/load',urlencodedParser,function (req, res) { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type","application/json;charset=utf-8") let path = Date.now()+'.png' let data={}; let img = req.body.imgData; let base64 = img.replace(/^data:image\/\w+;base64,/, ""); let dataBuffer = new Buffer(base64,'base64'); fs.writeFile(path,dataBuffer,function (err) { if(err){ data.info="请求失败" res.end(JSON.stringify(data)) }else{ data.info="请求成功" res.end(JSON.stringify(data)) } }) })
到这里,一个简单的图片上传就完成了。