Home > Article > Web Front-end > Let’s analyze how uni-app implements uploading pictures
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.
Recommended: "uniapp tutorial"
Applicationuni-app
When 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;
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 completeuni-file-picker
Components, file selection, uploading touniCloud
'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>
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); } });}
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] });}
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--; } } })}}
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; });}
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
Upload 3 pictures/delete pictures
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.
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!
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)
{ "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.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.
uni.previewImage()Implemented without any pitfalls, you can use it according to the portal parameters according to your needs.
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!