Home  >  Q&A  >  body text

javascript - JS image compression and upload as file

Use JS image compression to upload in WEBKIT.
Compress the image when selecting the image and obtain the BASE64 data of the image.
Then upload the image in the form of File when submitting the form.
The BASE has been obtained Data,
But the uploaded file is also BASE64 data and File

cannot be used directly.

Upload in the form of multipart/form-data

The problem is that 'the uploaded file is also BASE64 data and File cannot be used directly'

Hope to get suggestions to solve the problem, or a better way to upload ('under the premise of uploading in multipart/form-data mode')

淡淡烟草味淡淡烟草味2732 days ago1670

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-05-18 11:00:12

    Why do you have to spell form-data yourself? Since it is compressed using canvas, the browser must already support formData.

    Method 1: Use formData API instead of splicing it yourself

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload', true);
    
    var formData = new FormData();
    formData.append(name, value);
    formData.append(name, fileBlob, filename);
    
    xhr.send(formData);

    Method 2: Spell it yourself

    Compression uses canvas, calls canvas's toBlob object, and then uses fileReader's readAsBinaryString method to get the binary string of the blob object. This binary string is what needs to be filled in under the content-disposition of formdata.

    Your code is a bit messy. It seems that imageView.attr('src') gets the base64 dataURI of the compressed image. See if there is a way to get the binary String directly. If not, you can get the blob of the compressed image. Objects are also fine. Use fileReader to convert them yourself. If that doesn't work, use your dataURItoBlob object to convert the base64 dataURI into a blob, and then convert it into a binary string.

    bodyData += imageUrl === null ? '' : dataURItoBlob(imageUrl);
    // 这一句要改成
    
    var resizedImageBlob = dataURItoBlob(imageUrl);
    var reader = new FileReader();
    reader.onloadend = function () {
      bodyData += this.result;
    };
    reader.readAsBinaryString(resizedImageBlob);
    
    // 鉴于你代码本身有一个each循环,bodyData 最后还要 append 一个 boundary因为把 blob 转成二进制字符串的过程是异步的,这里的控制逻辑肯定要修改

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-18 11:00:12

    Convert the image to base64, why not upload it directly using the form? . .

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-18 11:00:12

    Visually inspect canvas-compressed images? Then convert it directly to binary and upload it

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-18 11:00:12

    The backend receives BASE64 decoding and processes it and converts it to FILE

    reply
    0
  • Cancelreply