uniapp小程序解决不能上传文件/图片问题

uniapp小程序解决不能上传文件/图片问题

当前uniapp微信小程序无法使用formData( )来上传文件/图片,会出现FormData is not defined 问题,
而官方给的uni.uploadFile()也是看的懵懵懂懂。

解决方法

使用uni-app提供的uni.uploadFile()来上传文件/图片。
uni.uploadFile( )官方API

uni.uploadFile({
    
    
	url: '后台接口路径',
	filePath: sourceFile.tempFilePaths[0],
	name: 'file',   //对应后台接口参数名
	method: 'POST',
	header: {
    
    
		"Authorization": '生成的token'
	},
	formData: {
    
    
		//要上传的文件
		file: sourceFile.tempFiles[0]
	},
	success(res) {
    
    
		console.log(res);
		if (res.path) {
    
    
		that.imageUrls = res.path;
		console.log(that.imageUrls);
		}
	},
	fail(res) {
    
    
		console.log(res);
		uni.showToast({
    
    
		icon: 'error',
		title: '图片上传失败!'
		})
	}
})

其中sourceFile是你选择要上传的文件/图片,包括tempFiles和tempFilePaths两部分。

sourceFile

注意

filePath放你的临时文件存储路径,也就是

filePath: sourceFile.tempFilePaths[0]

formData放你要上传的文件

formData: {
    
    
	file: sourceFile.tempFiles[0]
}
自己也是尝试了好多次,想必大家也会碰上上传文件之类的问题,可以试试这种方式。

猜你喜欢

转载自blog.csdn.net/qq_45740997/article/details/130139879
今日推荐