05- 微信小程序上传文件uniapp

296 阅读1分钟

一、上传文件

// 上传图片
function uploadImage(url: string, su_title: string, err_title: string) {
	return new Promise((resolve, reject) => {
    // 拿到文件
		uni.chooseMedia({
			count: 1,
			mediaType: ['image'],
			sizeType: ['compressed'],
			success: (res: any) => {
				console.log(res);
				uni.showLoading({ title: su_title, mask: true });
        // 上传到后端
				uni.uploadFile({
					url,
					filePath: res.tempFiles[0].tempFilePath,
					name: 'file',
					header: { accept: 'application/json' },
					success: (res_img: any) => {
						resolve(res_img);
						uni.hideLoading();
					},
					fail: (err_img: any) => {
						reject(err_img);
						uni.showToast({ title: err_title, icon: 'error', duration: 1000 });
					},
				});
			},
		});
	});
}