javascript - JS image compression and upload as file
淡淡烟草味
淡淡烟草味 2017-05-18 10:58:12
0
4
1596

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')

淡淡烟草味
淡淡烟草味

reply all(4)
左手右手慢动作

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 转成二进制字符串的过程是异步的,这里的控制逻辑肯定要修改
给我你的怀抱

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

仅有的幸福

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

巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!