uniapp使用uni.uploadFile上传图片文件,发送form-data请求

uni.uploadFile上传图片文件

使用uniapp开发混合app时碰到后台需要发送multipart/form-data请求 ,可以直接使用uni.uploadFile上传文件的同时将后台需要的其他 请求参数放在formData中一并发送

  1. 单文件发送请求
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. 多文件发送
<--定义一个 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发送form-data请求无效

将header中的Content-Type改成"application/x-www-form-urlencoded"或者"multipart/form-data"都无法成功发送请求

uniapp不支持 new FormData

亲测uniapp不支持直接new FormData()以及new window.FormData()
在这里插入图片描述

TypeError: Cannot read property ‘indexOf’ of undefined

猜你喜欢

转载自blog.csdn.net/qq_44090577/article/details/114257037