Advanced cross platform application development: uploading pictures with uni app

1, Foreword

When using uni App to develop cross platform App projects, the functional requirements for uploading pictures, documents and other resources are very common: click the picture frame button to select picture upload, click each picture to preview, and click the delete icon of each picture to delete the corresponding picture. The basic function points are as follows:

  • Select pictures from local album or upload pictures with camera;
  • You can preview the selected uploaded pictures;
  • Delete the wrong or unselected picture;

2, Project practice

After study uni-app Portal, official website, recommended application Uni The chooseimage (object) interface selects pictures from the local album or takes pictures with the camera.

For the portal mentioned

Most photos are selected for uploading. The uni ui encapsulates a more complete uni file picker component. Files are selected and uploaded to the free storage and cdn of uniCloud, which is a one-stop integration. Highly recommended.

⚠️ I don't recognize it. Through practice, it can only realize that the client can upload image resources to the uniCloud background server, and does not support the local server. Therefore, it does not meet the functional requirements and should be used with caution.

The general logic of the project implementation page is as follows, and the complete page implementation logic can be moved step by step< Uni app realizes image upload, deletion, preview and compression >Download.

View rendering

<template>
	<view class="center">
		<!-- Upload pictures -->
		<view class="uploadClass">
			<view class="imgClass" v-for="(item, i) in imgList" :key='i' @click="viewImage(i, imgList)">
				<image style="width: 100%;height: 100%;" :src="item"></image>
				<view @click.stop="delImg(i, imgList, imgsID)" style="display: inline;">
					<uni-icons type="closeempty" class="closeClass" size="20"></uni-icons>
				</view>
			</view>
			<view v-show='curTotal < 3' class="cameraClass" @tap="upload">
				<image style="width: 48rpx; height: 38rpx;" src="@/static/appCenter/zhaoxiangji@2x.png"></image>
			</view>
			<!-- Picture quantity prompt -->
			<view class="totalClass">{{curTotal}}/3</view>
		</view>
</template>

JS logic layer - image upload

// Picture selection upload
upload() {
	var _self = this;
	// Picture selection. Only one picture can be selected at a time
	uni.chooseImage({
		count: 1,
		sizeType: ['original', 'compressed'], //You can specify whether to use the original image or compressed image. Both are available by default
		sourceType: ['album', 'camera'], //Select from album and camera
		success: function (res) {
			console.log('res:', res)
			_self.curTotal++;
			_self.imgList.push(res.tempFilePaths[0]);
			const tempFilePaths = res.tempFilePaths[0];
			// Picture upload
			const uploadTask = uni.uploadFile({
				url : 'http://22.189.25.91:9988 / admin / sys file / upload ', / / post request address
			    filePath: tempFilePaths,
			    name: 'file',  // To be confirmed
			    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);
		}
   });
}

JS logic layer - picture preview

/**
 * Picture preview
 * @param {Object} i Selected picture index
 * @param {Object} imgList Self encapsulated image array
 */
viewImage(i, imgList) {
	let imgurl = []
	imgList.forEach(item => imgurl.push(item))
	uni.previewImage({
		urls: imgurl,
		current: imgList[i]
	});
}

JS logic layer - image deletion

/** Picture deletion
 * @param {Object} i Delete index of picture
 * @param {Object} imgList Self encapsulated image array
 */
delImg(i, imgList, imgsID) {
	uni.showModal({
		title: 'Tips',
		content: 'Are you sure you want to delete the photo?',
		cancelText: 'cancel',
		confirmText: 'determine',
		success: res => {
			if(res.confirm) {
				imgList.splice(i, 1);
				imgsID.splice(i, 1);
				this.curTotal--;
			}
		}
	})
}
}

JS logic layer - picture compression

// src: compress the path to convert the original picture
// _ This: the current this. If you don't want to pass this, you can change this function to an arrow function
// Callback: callback function, details chooseImage method
function compressImage(src, _this, callback) {
	var dstname = "_doc/IMG-" + (new Date()).valueOf() + ".jpg"; //Set the path of the compressed picture 
	var width, height, quality;
	width = "80%";
	height = "80%";
	quality = 80;
	// See the HTML5 + document for details = = > 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;
		});
}

be careful ⚠️: Image compression shall be carried out before image upload. Due to the long time of image compression, await shall be used to compress the image before uploading, otherwise the upload will be carried out before compression.

The application effect is as follows:
Take a picture or select a picture from an album / upload a picture

Upload 3 pictures / delete pictures

3, Summary of knowledge points

3.1 implementation principle

Client through Uni The chooseimage () method selects local album pictures or photos, obtains the temporary file path of a local resource, and then passes through Uni. Com in the form of POST request The UploadFile () method uploads the local resources to the developer server, and the content type in the POST request is multipart / form data.

3.2 precautions

  • ⚠️ Picture selection application Uni For the implementation of chooseimage(), please be careful to use the so-called more perfect uni file picker component encapsulated by uni ui. It selects and uploads resource files to the free storage and cdn of uniCloud. It is a one-stop integration and cannot be modified by individuals. Strongly recommended not to use!

  • ⚠️ Image upload application Uni Uploadfile() implementation, uploadfileres returned by the callback function after successful upload Data is a String type, and JSON needs to be applied when converting to an object Parse() parse.

    JSON.parse(uploadFileRes.data).data.fileId)
    
    {
    	"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"
    }
    
  • uni. The name attribute in the parameter description part of uploadfile() object is the key corresponding to the file to be uploaded. The developer can obtain the binary content of the file through this key on the server side. The front and back ends should be consistent with this key, otherwise the service will not be able to request.

  • Picture preview application Uni Previewimage() is implemented, but there is no pit. You can use it according to the portal parameters according to your needs.

4, Learning Corner

Keywords: Javascript Front-end Vue.js

Added by mhodge87 on Sun, 20 Feb 2022 15:27:10 +0200