簡單的圖片上傳(base64)
阿新 • • 發佈:2019-01-23
小菜鳥一枚,朋友問到圖片上傳,就寫了個小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)) } }) })
到這裡,一個簡單的圖片上傳就完成了。