Home > Web Front-end > uni-app > body text

Let's analyze how uni-app implements uploading pictures

WBOY
Release: 2022-03-01 17:51:29
forward
21965 people have browsed it

This article brings you relevant knowledge about uniapp, mainly including how to upload images. Let’s take a look at how to implement it. I hope it will be helpful to everyone.

Let's analyze how uni-app implements uploading pictures

Recommended: "uniapp tutorial"

1. Foreword

Applicationuni-appWhen developing cross-platform App projects, it is very common to upload resources such as pictures and documents. Functional requirements are very common: click the photo frame button to select a picture to upload, click on each picture to preview, and click on each picture delete icon to delete the corresponding picture. The basic functions are as follows:

  • Select pictures from the local album or use the camera to take pictures and upload pictures;
  • You can preview the selected uploaded pictures;
  • Delete the selected pictures. Wrong or unselected pictures;

2. Project practice

After studying the uni-app portal, the official website recommends the applicationuni.chooseImage(OBJECT)Interface to select pictures from the local album or use the camera to take pictures.

For the

mentioned in the portal, most of the photos are selected for uploading, uni ui encapsulates a more complete uni-file-picker Components, file selection, uploading to uniCloud's free storage and CDN, one-stop integration. Highly recommended.

I don’t agree with it. It can be seen from practice that this interface can only enable the client to upload image resources to the uniCloud background server. It does not support local servers, so it does not To meet functional requirements, use with caution.

The general logic of the project implementation page is as follows. The complete page implementation logic can be downloaded from "Uni-app Implements Image Uploading, Deletion, Preview, and Compression".

View Rendering

<template>
	<view>
		<!-- 上传图片 -->
		<view>
			<view>
				<image></image>
				<view>
					<uni-icons></uni-icons>
				</view>
			</view>
			<view>
				<image></image>
			</view>
			<!-- 图片数量提示 -->
			<view>{{curTotal}}/3</view>
		</view></view></template>
Copy after login

JS Logic Layer-Picture Upload

// 图片选择上传upload() {
	var _self = this;
	// 图片选择,只支持一次选择一张图片
	uni.chooseImage({
		count: 1,
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album', 'camera'], //从相册、相机选择
		success: function (res) {
			console.log('res:', res)
			_self.curTotal++;
			_self.imgList.push(res.tempFilePaths[0]);
			const tempFilePaths = res.tempFilePaths[0];
			// 图片上传
			const uploadTask = uni.uploadFile({
				url : 'http://22.189.25.91:9988/admin/sys-file/upload', // post请求地址
			    filePath: tempFilePaths,
			    name: 'file',  // 待确认
			    header: {
					'Content-Type': 'multipart/form-data',
					'Authorization': getApp().globalData.token || 'Basic YXBwOmFwcA=='
				},
				success: function (uploadFileRes) {
					console.log('Success:', uploadFileRes);
					_self.imgsID.push(JSON.parse(uploadFileRes.data).data.fileId);
					console.log('_self.imgsID:', _self.imgsID)
				},
				fail: function (uploadFileFail) {
					console.log('Error:', uploadFileFail.data);
				},
				complete: ()=> {
					console.log('Complete:');
				}
			});
		},
		error : function(e){
			console.log(e);
		}
   });}
Copy after login

JS Logic Layer-Picture Preview

/**
 * 图片预览
 * @param {Object} i 选择的图片索引
 * @param {Object} imgList 自行封装的图片数组
 */viewImage(i, imgList) {
	let imgurl = []
	imgList.forEach(item => imgurl.push(item))
	uni.previewImage({
		urls: imgurl,
		current: imgList[i]
	});}
Copy after login

JS logical layer-picture deletion

/** 图片删除
 * @param {Object} i 删除图片的索引
 * @param {Object} imgList 自行封装的图片数组
 */delImg(i, imgList, imgsID) {
	uni.showModal({
		title: '提示',
		content: '确定要删除照片吗?',
		cancelText: '取消',
		confirmText: '确定',
		success: res => {
			if(res.confirm) {
				imgList.splice(i, 1);
				imgsID.splice(i, 1);
				this.curTotal--;
			}
		}
	})}}
Copy after login

JS logical layer-picture compression

// src: 压缩转换原始图片的路径// _this: 当前的this,如果不想传递this可将该函数改为箭头函数// callback: 回调函数,详情chooseImage方法function compressImage(src, _this, callback) {
	var dstname = "_doc/IMG-" + (new Date()).valueOf() + ".jpg"; //设置压缩后图片的路径 
	var width, height, quality;
	width = "80%";
	height = "80%";
	quality = 80;
	// 具体情况可查看HTML5+文档 ===> http://www.html5plus.org/doc/zh_cn/zip.html#plus.zip.compressImage
	plus.zip.compressImage({
			src: src,
			dst: dstname,
			overwrite: true,
			quality: quality,
			width: width,
			height: height		},
		function(event) {
			callback(event.target, dstname, _this);
		},
		function(error) {
			return src;
		});}
Copy after login

Note: Compress the image before uploading it. Since the image compression time is too long, await should be used to compress the image before uploading it, otherwise the upload will be performed before the compression.

The application effect is as follows:
Take a picture or select a picture from the album/upload a picture
Lets analyze how uni-app implements uploading picturesLets analyze how uni-app implements uploading pictures
Upload 3 pictures/delete pictures
Lets analyze how uni-app implements uploading picturesLets analyze how uni-app implements uploading pictures

##3. Summary of knowledge points

3.1 Implementation principle

Client pass

The uni.chooseImage() method selects local album pictures or takes pictures, obtains the temporary file path of a local resource, and then uses POST request method through uni.uploadFile() The method uploads local resources to the developer server, and the content-type in the POST request is multipart/form-data.

3.2 Notes

  • Image selection application

    uni.chooseImage()implementation, please use uni uiencapsulated with caution The so-called more complete uni-file-picker component selects and uploads resource files to the free storage of uniCloud and cdn, providing one-stop integration. Individuals cannot modify it. Strongly recommended not to use!

  • Image upload application

    uni.uploadFile()implementation, the uploadFileRes.data returned by the callback function after the upload is successful is a String Type, you need to apply JSON.parse() when converting objects.

    JSON.parse(uploadFileRes.data).data.fileId)
    Copy after login
    {
    	"data": "{\"code\":0,\"msg\":null,\"data\":{\"bucketName\":\"cicc\",\"fileName\":\"5aaa39d669224ffb869b60d245b0751a.jpg\",\"original\":\"1644999553865_mmexport1644913914292.jpg\",\"url\":\"/admin/sys-file/cicc/5aaa39d669224ffb869b60d245b0751a.jpg\",\"fileId\":\"172\"}}",
    	"statusCode": 200,
    	"errMsg": "uploadFile:ok"}
    Copy after login
  • uni.uploadFile() The name attribute in the OBJECT parameter description section is the key corresponding to the file to be uploaded. , Developers can obtain the binary content of the file through this key on the server side. The front-end and back-end should be consistent with this key, otherwise the service will not be able to request.
    Lets analyze how uni-app implements uploading pictures

  • Image preview application

    uni.previewImage()Implemented without any pitfalls, you can use it according to the portal parameters according to your needs.

Recommended: "

uniapp learning tutorial"

The above is the detailed content of Let's analyze how uni-app implements uploading pictures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template