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"
1. Foreword
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;
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 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.
- Image selection application
uni.chooseImage()
implementation, please use
uni uiencapsulated with caution The so-called more complete
uni-file-pickercomponent selects and uploads resource files to the free storage of
uniCloudand
cdn, providing one-stop integration. Individuals cannot modify it. Strongly recommended not to use!
- Image upload application
uni.uploadFile()
implementation, the
uploadFileRes.datareturned by the callback function after the upload is successful is a
StringType, 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
nameattribute in the OBJECT parameter description section is the
keycorresponding to the file to be uploaded. , Developers can obtain the binary content of the file through this
keyon the server side. The front-end and back-end should be consistent with this key, otherwise the service will not be able to request.
- Image preview application
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

When choosing between UniApp and native development, you should consider development cost, performance, user experience, and flexibility. The advantages of UniApp are cross-platform development, rapid iteration, easy learning and built-in plug-ins, while native development is superior in performance, stability, native experience and scalability. Weigh the pros and cons based on specific project needs. UniApp is suitable for beginners, and native development is suitable for complex applications that pursue high performance and seamless experience.

In the field of mobile application development, Flutter and uniapp are two cross-platform development frameworks that have attracted much attention. Their emergence enables developers to quickly and efficiently develop applications that support multiple platforms simultaneously. However, despite their similar goals and uses, there are some differences in details and features. Next, we will compare Flutter and uniapp in depth and explore their respective characteristics. Flutte is an open source mobile application development framework launched by Google. Flutter

Recommended component library for uniapp to develop small programs: uni-ui: Officially produced by uni, it provides basic and business components. vant-weapp: Produced by Bytedance, with a simple and beautiful UI design. taro-ui: produced by JD.com and developed based on the Taro framework. fish-design: Produced by Baidu, using Material Design design style. naive-ui: Produced by Youzan, modern UI design, lightweight and easy to customize.
