The Uniapp applet allows you to select pictures from the album/take pictures and upload them directly

Recently, I encountered a need when working on a mini program project, which is to directly call the backend interface to upload pictures after selecting/taking pictures from the album. I think if you ignore that the mini program is not run based on the browser, then think about what to do. It would be a big mistake to send files in file format to the backend... because the browser-based JS environment does not have classes such as FormData, File, etc... Take a look at the renderings...

 

First, let’s take a look at the UNI API for selecting pictures/taking pictures from the album. This is nothing, just call it directly according to the document... 

// 从相册选图
uni.chooseImage({
	count: 12, // 最多可以选择的图片张数,默认9
	sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
	sourceType: ['album'], //album 从相册选图,camera 使用相机
	success: (res) => {
        // TODO SUCCESS
    }
})

// 使用相机
uni.chooseImage({
	count: 12, // 最多可以选择的图片张数,默认9
	sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
	sourceType: ['camera'], //album 从相册选图,camera 使用相机
	success: (res) => {
        // TODO SUCCESS
    }
})

// 从相册选图/使用相机
uni.chooseImage({
	count: 12, // 最多可以选择的图片张数,默认9
	sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
	sourceType: ['album ','camera'], //album 从相册选图,camera 使用相机
	success: (res) => {
        // TODO SUCCESS
    }
})

Through the above method, it is found that through res in success, the array tempFilePaths of the temporary image file can be obtained. The temporary file can be handed over to the backend for processing directly by calling the interface. Since the backend did not accept the temporary file at that time, I will do one more step to process the temporary file into base64, and then pass it to him...

Let’s briefly talk about how to convert a temporary file to base64. First, get the file processor through uni.getFileSystemManager(), because you need a method to read the file, and then traverse the array of temporary files to convert in sequence, because the method of reading the file is asynchronous. Yes, Promise.all needs to be processed here, otherwise the base64 array you pass to the backend will still be the empty array when it was declared...

 

Promise.all(
	res.tempFilePaths.map(item => {
		return new Promise((resolve, reject) => {
			fs.readFile({
				filePath: item,
				encoding: 'base64',
				success: res => {
					resolve('data:image/png;base64,' + res
						.data)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	})
).then(results => { // 在这里处理所有文件的内容
	that.uploadLivePic(results)
})

 You have successfully uploaded the picture here. If you think it is helpful to you, you can leave a star...

Guess you like

Origin blog.csdn.net/m0_52510500/article/details/132805526