0
点赞
收藏
分享

微信扫一扫

220-jquery,将base64的图片,转为file文件,并通过$.ajax上传

var base64 = '';
const blob = dataURLToBlob(base64);
  const file = blobToFile(blob, 'image.jpg');

  uploadImage(file);
  
  
function dataURLToBlob(base64) {
  const parts = dataURL.split(';base64,');
  const contentType = parts[0].split(':')[1];
  const byteCharacters = atob(parts[1]);
  const byteArrays = [];

  for (let i = 0; i < byteCharacters.length; i++) {
    byteArrays.push(byteCharacters.charCodeAt(i));
  }

  return new Blob([new Uint8Array(byteArrays)], { type: contentType });
}

function blobToFile(blob, fileName) {
  return new File([blob], fileName, { type: blob.type });
}
function uploadImage(file) {
            var formData = new FormData();
            formData.append("picFile", file);
            // 发送 AJAX 请求上传文件
            $.ajax({
                url: "/upload/img-upload-local", //
                type: "POST",
                async:false,
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    $(".div1").hide();
                    $(".div2").hide();
                    $("#showImg").attr("src",res.url)
                    $(".imgDiv").show();
                    closeCamera();

                },
                error: function() {
                    alert("上传失败");
                }
            });
        }
举报
0 条评论