简单的图片上传(base64)

小菜鸟一枚,朋友问到图片上传,就写了个小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))
      }
    })
})
到这里,一个简单的图片上传就完成了。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值