unipp uses uview to directly transmit to Qiniu Cloud (file bold data flow is converted into file file flow)

Long application scenario: uview2 uniapp h5

Upload the avatar individually, delete the preview function, and directly upload the front-end to Qiniu Cloud

Knowledge point: Convert file bold data flow to file file flow

Because the callback function file of uview is not of file type

Link: File.File() - Web API Interface Reference | MDN (mozilla.org)

const imgBlob = await fetch(数据流url).then(r => r.blob())
let file=new File([imgBlob], event.file.name ,{ type:'image/png'})

1、html

				<div @click="onUpload">上传</div>
				<u-upload
					:fileList="fileList1"
					@afterRead="afterRead"
					name="1"
					:multiple="false"
					:maxCount="1"
					:deletable="true"
					:previewImage="true"
					:auto-upload="true"
					@delete="deleteImage"
				></u-upload>




	data() {
		return {
			fileList1: [],
}

2.1 Uniapp’s native API does not use components and is not recommended for use that requires user interaction, because page interactions such as image upload, upload, deletion, etc. are very troublesome to write.

		// 上传图片
		onUpload() {
			uni.chooseImage({
				//从手机相册选取图片(获取文件信息)
				count: 1, // 默认9
				sizeType: ['compressed', 'original'],
				sourceType: ['album', 'camera'],
				success: chooseImageRes => {
					//返回的文件信息
					const filePath = chooseImageRes.tempFilePaths[0]; // 文件数据流blob信息
					const file = chooseImageRes.tempFiles[0]; // 文件文件流信息
					console.log(chooseImageRes, filePath, file, 'tempFilePaths');
					uni.uploadFile({
						url: 'https://up-z1.qiniup.com', //七牛云服务器地址
						filePath,
						file,
						name: file.name,
						formData: {
							//HTTP 请求中其他额外的 form data
							key: new Date().getTime() + file.name,
							token: this.token,
							file
						},
						success: uploadFileRes => {
							//将本地资源上传到开发者服务器(文件上传)
							if (uploadFileRes.statusCode == 200) {
								let key = JSON.parse(uploadFileRes.data).key;
								let partImgUrl = this.$config.domainURL + '/' + key;
								console.log(key, partImgUrl, 'uploadFileRes');
							}
						},
						fail: err => {
							console.log('fail', err);
						}
					});
				}
			});
		},

2.2 Choose one of the following two uploadFilePromise methods. I use the second one.


		// 新增图片
		async afterRead(event) {
			console.log(event, event.file.url, '上传function');
			const imgBlob = await fetch(event.file.url).then(r => r.blob());
			let lists = [].concat(event.file);
			console.log(this[`fileList${event.name}`], 'this[`fileList${event.name}`]');
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map(item => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				let file = new File([imgBlob], event.file.name, { type: 'image/png', path: event.file.url });
				const result = await this.u(file);
				console.log(result, 'relust');
				let key = JSON.parse(result.data).key;
				let partImgUrl = this.$config.domainURL + '/' + key;
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: partImgUrl
					})
				);
				fileListLen++;
			}
		},	

//  方法1
	uploadFilePromise(file) {    
			console.log(file, '上传function');
			let that = this;

			const qiniuUploadInfo = {
				file: file, //文件对象
				key: new Date().getTime() + file.name, //文件资源名称
				token: this.token //从后端获取的uplodaToken
			};
			const observable = qiniu.upload(
				qiniuUploadInfo.file,
				qiniuUploadInfo.key,
				qiniuUploadInfo.token,
				{
					fname: file.name, // 文件原文件名
					params: {}, // 用来放置自定义变量
					mimeType: null // 用来限制上传文件类型,为 null 时表示不对文件类型限制;eg: ["image/png", 	  "image/jpeg"]
				},
				{
					useCdnDomain: true, //cdn加速
					region: qiniu.region.z1 //区域
				}
			);
			console.log(qiniuUploadInfo, observable, '上传function');
			//上传开始
			observable.subscribe({
				next(res) {
					console.log('next', res);
				},
				error(err) {
					console.log('err', err);
				},
				complete(res) {
					//来到这里就是上传成功了。。
				}
			});
		},

//  方法2
		uploadFilePromise(file) {
			console.log(file, 'file');
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'https://up-z1.qiniup.com', //七牛云服务器地址
					file,
					name: file.name,
					formData: {//HTTP 请求中其他额外的 form data
						
						key: new Date().getTime() + file.name,
						token: this.token,
						file
					},
					success: res => {//将本地资源上传到开发者服务器(文件上传)
						
						if (res.statusCode == 200) {
							setTimeout(() => {
								resolve(res);
							}, 1000);
						}
					},
					fail: err => {
						console.log('fail', err);
					}
				});
			});
		},

3. Delete function

		deleteImage(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
		},

Guess you like

Origin blog.csdn.net/m0_65720832/article/details/132214337