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.

  1. 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)
					}
				})
  1. 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()
Insert picture description here

TypeError: Cannot read property ‘indexOf’ of undefined

Guess you like

Origin blog.csdn.net/qq_44090577/article/details/114257037