At first, we used axios encapsulated by lab bosses to upload pictures with formData. However, the form data passed to the background is empty, and the printed form does exist. Baidu searched for a big push, so it learned from Baidu's practice.
1. Introduce Axios import Axios from'axios';
2. Create a new axios.
const instance = axios.create({
withCredentials:true // indicates whether credentials are required for cross-domain requests, defaulting to false
})
instance.post('url',formData).then(res=>{
})
.catch(err=>{
console.log(err)
})
At this time, you can see formData coming out, a little happy, so immediately tried to upload pictures, but the background still did not receive pictures, the image value passed is as follows
Then after a discussion with the background, I realized that I was transmitting the base64 encoding of the picture, and the background needed to receive the file file object, so Baidu once again converted Base64 into file form.
The complete code is as follows
addPhoto(){ let self = this const form = new FormData() self.fileList.forEach((file) => { // fileList An array of files to upload self.imageUrl = file.url || file.thumbUrl form.append('image', self.dataURLtoFile(self.imageUrl,file.name)) }); form.append('seedbedId', self.seedbedId) const instance = axios.create({ withCredentials:true }) instance.post('url',form).then(res=>{ if(res.data.code===2000){ console.log(res.data.message) }else{ console.log(res.data.message) } }) .catch(err=>{ console.log(err) }) }, dataURLtoFile(dataurl, filename) {//take base64 Converting to a file var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type:mime}); },
So far, the upload of pictures has come to an end.