uniAPP PUT图片上传

836 阅读1分钟

uniAPP图片上传

uniapp通常在将图片上传阿里云的时候,会有一些问题,特别是在后端要求使用PUT上传的时候,所以说一下我的解决方案。

微51.jpg

注意:需要使用到axios和一个base64的库

ext.dcloud.net.cn/plugin?id=1… ---这个是base64的插件,可以直接下载使用

//直接导入就可以了
import {
		pathToBase64,
		base64ToPath
	} from "../../js_sdk/mmmm-image-tools/index.js"

终端命令安装axios $ npm install axios

	import axios from "axios";

首页就是需要图片的格式转换一下,因为uniapp在浏览器预览时上传图片是不一样的,移动端是没有 new FormData() 所以需要先转成 base64 再转成 File 类型,不然就算上传成功,图片也会是无法查看或者是乱码。

1.先获取到图片的本地文件路径列表

	selectImg() {
		let than = this
		uni.chooseImage({
			count: 20,
			sizeType: ['original', 'compressed'],
			sourceType: ['album'],
			success: function(res) {
				console.log(res)
				var tempFilePaths = res.tempFilePaths;
				than.uploadFilePromise(tempFilePaths[0])
			}
		});
	},

2.有两种方法可以使用分别是axios和原生的XHR

axios -- 方便检查上传的进度和返回的状态,但是代码较多

XHR -- 代码较少,但是不方便检查上传的进度和返回的状态

uploadFilePromise(path) {
	let than = this
	pathToBase64(path)
		.then(base64 => {//转成base64
			//console.log(base64)
			var arr = base64.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			var fileResult = new File([u8arr], "filename.jpg", {
				type: mime
			});
			//console.log(fileResult);
			axios({
				method: 'PUT',
				url: "",//上传地址
				data: fileResult,
				processData: false,
				headers: {
					"content-type": ''
				},
			}).then(res => {
				console.log(res)
				if (res.status === 200) {
                                //上传成功
					console.log(res)
				} else if (res.status !== 200) {
                                //上传失败
				}
			})
			/* var xhr = new XMLHttpRequest() //这块也是能用
			xhr.open('PUT', this.uploadingUrl)
			xhr.setRequestHeader('Content-type', '')
			xhr.send(fileResult)
			xhr.onreadystatechange = function() {
				if (xhr.status === 200) {
                                //上传成功
				} else {
                                //上传失败
				}
			} */
		})
		.catch(error => {
			console.error(error)
		})
},