Blob temporary path to File object
Recently, I found a problem in using taro-UI.
Problem representation
When uploading an image, taro-UI only provides an image selector that can return a temporary path to the image, similar to the following:
{
"url":"Blob: http://10.1.10.122:10086/4ebc5d64-bd9a-4994-8212-addf476ba2c2"."file": {
"path":"Blob: http://10.1.10.122:10086/4ebc5d64-bd9a-4994-8212-addf476ba2c2"."size":370876."type":"image/jpeg"."lastModifiedDate":"The 2020-12-23 T02: canst. 661 z"."lastModified":1608691115661."name":"1608691115661.jpeg"}}Copy the code
You can see the basic information of the image (size, type, long transmission time, image name). It’s all included, including a temporary path that starts with blob: HTTP:.
solution
This can’t be passed directly to the backend. It needs to be converted to File format via multipart/form-data protocol.
The solution
Convert the temporary path to a File object and add it to form-data.
/ / which
// imgObj = the object above
/ / imgObj. = blob url: http://10.1.10.122:10086/4ebc5d64-bd9a-4994-8212-addf476ba2c2
const imgBlob = await fetch(imgObj.url). then(r= > r.blob())
const imgFile = new File([imgBlob], imgObj.file.name , { type: imgBlob.type })
const formData = new FormData();
formData.append("file", imgFile);
const res: any = await http.post("/api/uploadFile",formData);
Copy the code