In fact, there is another Canvas method which is toBlob. The file object inherits from the Blob object. In fact, the file object inherits from the Blob object. That is, the properties and methods of the BLOB object.

function dataURLtoFile (dataurl, Filename) {let arr = dataur.split (',') let mime = arr[0]. Match (/ (.*?) ; /)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], filename, { type: mime }) }

The normal method of processing an image uses the defined dataURLtoFile method

Function handleImg (file) {let read = new FileReader() read.readAsDataURL(file) return new Promise(function (resolve, reject) { read.onload = function (e) { let img = new Image() img.src = e.target.result img.onload = function () { // Canvas let canvas = document.createElement('canvas') let CTX = canvas.getContext('2d') canvas. Width = this.width canvas.height = this.height ctx.drawImage(this, 0, 0, this.width, Base64 = Canvas. ToDataFile (File ['type'], 1) let files = DataDataFile (base64, 1) File. Name) resolve(files) // Use Blob Canvas. ToBlob (function(blob) {blob. LastModifiedDate = new Date().getTime(); blob.name = file.name resolve(blob) },file['type'], 1) } }}) }

Finally, when we upload, we call the handleIMG method to return the processed img

Async function Upload () {let formData = new formData () let _file = await handleIMG (' I am the img that needs to upload ') FormData.append ('file[]', _file, _file.name) // call uploading interface}

Finally, the interface is called to upload directly. Here is when uploading, the parameter _file.name must be added when using scheme 2, because during the upload process, the browser automatically named our file stream to BLOB, so it will cause the problem of incorrect upload file name