如何上传使用Blob转换为Blob的图像:http url php和javascript

时间:2018-11-14 18:10:23

标签: javascript image blob uploading

请上传文件转换为Blob网址时遇到问题,我希望将该网址上传到php端,这是我的html代码,很简单:

<form id="img_uploader" accept="image/*" enctype="multipart/form-data">
    <input id="upl_file" type="file" name="file" />
</form>

JavaScript代码:

$('#upl_file').on('change', function(e) {
    const img_file = e.target.files[0];
    const reader = new FileReader();
   reader.onload = (e)=> {
       const imgData = e.target.result;
       const onlyData = imgData.substring( imgData.split(",")[1] );

      //Convert the string to bytes
      var bytes = new Uint8Array(onlyData.length);

     for (var i = 0; i < onlyData.length; i++) {
         bytes[i] = onlyData.charCodeAt(i);
     }

    var mime = imgData.split(",")[0].split(":")[1].split(";")[0];

    // Make a Blob from the bytes
    const blob = new Blob([bytes], {type: mime});
    const urlCreator = window.URL || window.webkitURL;
    const blobUrl = urlCreator.createObjectURL(blob);

    var formData = new FormData();
    formData.append('file', blobUrl);

    $.ajax({
       url: 'https://prestastar.com/uploaded.php',
       data: formData,
       type: 'POST',
       contentType: false,
       processData: false,
       dataType: 'json',
       success: function(res) {
           console.log(res)
       },
       error: function(err) {
           console.log('Error happened', err.responseText);
       }
   });
 };

  reader.readAsDataURL(img_file);
}

如果我直接将“ blob”变量附加到formData上,则需要花费很长时间才能上传4mo,有什么帮助,建议吗?

先谢谢大家。

0 个答案:

没有答案