JS 读取本地文件转base64 上传到服务器

本文介绍了一种将商品评价中的图片文件转换为Base64字符串的方法,并通过JavaScript实现。该过程首先检查文件格式是否符合要求(如png、jpg等),然后使用FileReader API读取文件并将其转换为Base64格式,最后通过Ajax将Base64字符串发送到服务器进行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$("#qrcode").on("change", function(){
  var bs64 = base64(document.getElementById("qrcode"));
});
// 商品评价 图片转base64
// Process the file
// Precondition: expects image files, but works with others too
function base64(file) {
    var reader = new FileReader();
    var pos = file.target.files[0].name.lastIndexOf(".");
    var type = file.target.files[0].name.substring(pos + 1);

    if (type.toLowerCase() != "png" && type.toLowerCase() != 'jpg' && type.toLowerCase() != 'jpeg' && type.toLowerCase() != 'gif' && type.toLowerCase() != 'bmp') {
        alert("格式错误,请上传'png、jpg、jpeg、bmp、gif'格式文件");
        return;
    }
    num += 1;
    reader.onloadend = (
        function(e) {
            imgurl = e.target.result;
            updateBackground();
        }
    );

    // Read the file
    reader.readAsDataURL(file.target.files[0]);
}


// Return the data to the user
function updateBackground(){
  // urlElement.innerHTML = imgurl;
   
  jq.ajax({
    url:'user.php',
    data:{
      act:'update_pic',
      imgurl:imgurl
    },
    type:'post',
    dataType:'text',
    success:function(data){
      if(data == "error"){
        alert("上传失败,请重新操作");
      }else{
        jq("#comment_image").prepend("<input type='hidden' name='images[]' value='"+data+"'>");
        jq("#comment_image").prepend("<img width='70' height='70' src='"+imgurl+"' style='margin: 2px;'>");
        num-=1;
       sum+=1;
      }   
    }
  })

}

 

转载于:https://www.cnblogs.com/jh1994/p/5660775.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值