站长图库向大家介绍了uni-app实现上传图片等相关知识,希望对您有所帮助
本篇文章给大家带来了关于uniapp的相关知识,主要包括了怎样实现上传图片的相关问题,下面就一起来看一下应该怎样实现,希望对大家有帮助。

一、前言
应用uni-app开发跨平台App项目时,上传图片、文档等资源功能需求十分常见:点击相框按钮可选择图片上传,点击每一个图片可以进行预览,点击每个图片删除图标可删除对应图片。基本实现功能点如下:
本地相册选择图片或使用相机拍照上传图片;
可以预览选择上传的图片;
删除选错或不选的图片;
二、项目实战
经过研读uni-app门户,官网推荐应用uni.chooseImage(OBJECT)接口从本地相册选择图片或使用相机拍照。
对于门户提到的
选择照片大多为了上传,
uni ui封装了更完善的uni-file-picker组件,文件选择、上传到uniCloud的免费存储和cdn中,一站式集成。强烈推荐使用。
本人并不认可,经过实践可知,该接口只能实现客户端将图片资源上传到uniCloud后台服务器中,并不支持本地服务器,故并不满足功能需求,需谨慎使用。
项目实现页面大致逻辑如下,完整页面实现逻辑可移步《Uni-app 实现图片上传、删除、预览、压缩》下载。
视图渲染
<template> <view class="center"> <!-- 上传图片 --> <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> <!-- 图片数量提示 --> <view class="totalClass">{{curTotal}}/3</view> </view> </view></template>JS逻辑层-图片上传
// 图片选择上传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){  

