uniapp uses uni.uploadFile to upload image files and send form-data requests
uni.uploadFile upload image file
When you use uniapp to develop a hybrid app, you need to send multipart/form-data requests in the background. You can directly use uni.uploadFile to upload files and put other request parameters needed in the background in formData and send them together.
- Single file sending request
uni.uploadFile({
url:this.url,
filePath: tempFilePaths[0],
name: 'file',
formData:this.formdata,
header:{
"Content-Type": "multipart/form-data",
"token":this.token
},
success: (res) => {
if (res.data.code == 200){
console.log('请求成功_______________',res)
uni.showToast({
icon:'none',
title:'提交成功',
success: (res) => {
setTimeout(() => {
uni.navigateBack({
delta: 1
})
}, 1500)
}
})
}
},
fail:(err)=>{
console.log('请求失败_______________',err)
}
})
- Multiple file sending
<--定义一个 file 对象的数组为files 参数,file 对象的结构:-->
let imgs = this.imgList.map((value, index) => {
return {
name: "img" + index,
uri: value
}
});
uni.uploadFile({
url:this.url,
files:this.imgs,
formData:this.formdata,
header:{
"Content-Type": "multipart/form-data",
"token":this.token
},
success: (res) => {
if (res.data.code == 200){
console.log('请求成功_______________',res)
uni.showToast({
icon:'none',
title:'提交成功',
success: (res) => {
setTimeout(() => {
uni.navigateBack({
delta: 1
})
}, 1500)
}
})
}
},
fail:(err)=>{
console.log('请求失败_______________',err)
}
})
uni.request is invalid for sending form-data request
Changing the Content-Type in the header to "application/x-www-form-urlencoded" or "multipart/form-data" fails to send the request successfully
uniapp does not support new FormData
Pro test uniapp does not support direct new FormData() and new window.FormData()