插件ID:htz-image-upload    网站地址:图片 视频上传 预览 支持uniCloud上传 支持vue3【简单好上手】 - DCloud 插件市场

同时支持ios 安卓的视频预览功能,可选择添加/删除图片/视频,可以压缩(包括H5压缩)(解决了安卓10问题),支持上传到服务器后台,也支持uniCloud,可以在vue3使用,能满足大部分场景

附上修改后的代码  仅适用于我们的项目

<view class="video"><htz-image-upload :max="1":disabled="disDoTask"v-model="ceshiData" :sourceType="['camera']" :maxDuration="9999" mediaType="video":remove="!disDoTask"@uploadSuccess="ceshiUploadSuccess" :headers="{ token: token }":formData="{url: `${tasktitle}/${shopname}`,name:`${scoretitle}` }" :compress="true":quality="20" :action="baseUrl + '/index/Common/uploadFile'"></htz-image-upload>
</view>

组件中:

<template><view class="htz-image-upload-list"><view class="htz-image-upload-Item" v-for="(item,index) in uploadLists" :key="index"><view class="htz-image-upload-Item-video" v-if="isVideo(item)"><!-- #ifndef APP-PLUS --><video :disabled="false" :controls="false" :src="getFileUrl(item)"><cover-view class="htz-image-upload-Item-video-fixed" @click="previewVideo(getFileUrl(item))"></cover-view><cover-view class="htz-image-upload-Item-del-cover" v-if="remove && previewVideoSrc==''"@click="imgDel(index)">×</cover-view></video><!-- #endif --><!-- #ifdef APP-PLUS --><view class="htz-image-upload-Item-video-fixed" @click="previewVideo(getFileUrl(item))"></view><image class="htz-image-upload-Item-video-app-poster" mode="widthFix" :src="appVideoPoster"></image><!-- #endif --></view><image v-else :src="getFileUrl(item)" @click="imgPreview(getFileUrl(item))"></image><view class="htz-image-upload-Item-del" v-if="remove" @click="imgDel(index)">×</view></view><view class="htz-image-upload-Item htz-image-upload-Item-add" v-if="uploadLists.length<max && add"@click="chooseFile"><view class="videobox" v-if="disabled == false"><u-icon name="plus" color="979797" size="24"></u-icon></view><view class="videobox" v-else><u-icon name="minus-circle-fill" color="#ff6666" size="24"></u-icon></view><!-- + --></view><view class="preview-full" v-if="previewVideoSrc!=''"><video :autoplay="true" :src="previewVideoSrc" :show-fullscreen-btn="false"><cover-view class="preview-full-close" @click="previewVideoClose"> ×</cover-view></video></view><!--  --></view>
</template><style>.ceshi {width: 100%;height: 100%;position: relative;top: 0;left: 0;bottom: 0;right: 0;background-color: #FFFFFF;color: #2C405A;opacity: 0.5;z-index: 100;}
</style><script>export default {name: 'htz-image-upload',props: {max: { //展示图片最大值type: Number,default: 1,},chooseNum: { //选择图片数type: Number,default: 9,},name: { //发到后台的文件参数名type: String,default: 'file',},dataType: { //v-model的数据结构类型type: Number,default: 0, // 0: ['http://xxxx.jpg','http://xxxx.jpg'] 1:[{type:0,url:'http://xxxx.jpg'}]  type 0 图片 1 视频 url 文件地址 此类型是为了给没有文件后缀的状况使用的},remove: { //是否展示删除按钮type: Boolean,default: true,},add: { //是否展示添加按钮type: Boolean,default: true,},disabled: { //是否禁用type: Boolean,default: false,},sourceType: { //选择照片来源 【ps:H5就别费劲了,设置了也没用。不是我说的,官方文档就这样!!!】type: Array,default: () => ['album', 'camera'],},action: { //上传地址 如需使用uniCloud服务,设置为uniCloud即可type: String,default: '',},headers: { //上传的请求头部type: Object,default: () => {},},formData: { //HTTP 请求中其他额外的 form datatype: Object,default: () => {},},compress: { //是否需要压缩type: Boolean,default: true,},quality: { //压缩质量,范围0~100type: Number,default: 80,},value: { //受控图片列表type: Array,default: () => [],},uploadSuccess: {default: (res) => {return {success: false,url: ''}},},mediaType: { //文件类型 image/video/alltype: String,default: 'image',},maxDuration: { //拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。 (只针对拍摄视频有用)type: Number,default: 60,},camera: { //'front'、'back',默认'back'(只针对拍摄视频有用)type: String,default: 'back',},appVideoPoster: { //app端视频展示封面 只对app有效type: String,default: '/static/htz-image-upload/play.png',},},data() {return {uploadLists: [],mediaTypeData: ['image', 'video', 'all'],previewVideoSrc: '',}},mounted: function() {this.$nextTick(function() {this.uploadLists = this.value;if (this.mediaTypeData.indexOf(this.mediaType) == -1) {uni.showModal({title: '提示',content: 'mediaType参数不正确',showCancel: false,success: function(res) {if (res.confirm) {//console.log('用户点击确定');} else if (res.cancel) {//console.log('用户点击取消');}}});}});},watch: {value(val, oldVal) {//console.log('value',val, oldVal)this.uploadLists = val;},},methods: {isVideo(item) {let isPass = falseif ((!/.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item) && this.dataType == 0) || (this.dataType == 1 && item.type == 1)) {isPass = true}return isPass},getFileUrl(item) {var url = item;if (this.dataType == 1) {url = item.url}//console.log('url', url)return url},previewVideo(src) {this.previewVideoSrc = src;// this.previewVideoSrc =//     'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-fbd63a76-dc76-485c-b711-f79f2986daeb/ba804d82-860b-4d1a-a706-5a4c8ce137c3.mp4'},previewVideoClose() {this.previewVideoSrc = ''//console.log('previewVideoClose', this.previewVideoSrc)},imgDel(index) {let delUrl = this.uploadLists[index]this.uploadLists.splice(index, 1)this.$emit("input", this.uploadLists);this.$emit("imgDelete", {del: delUrl,tempFilePaths: this.uploadLists});// uni.showModal({//     title: '提示',//    content: '您确定要删除么?',//    success: (res) => {//       if (res.confirm) {//            // this.uploadLists.splice(index, 1)//          // this.$emit("input", this.uploadLists);//           // this.$emit("imgDelete", this.uploadLists);//           let delUrl = this.uploadLists[index]//             this.uploadLists.splice(index, 1)//             this.$emit("input", this.uploadLists);//          this.$emit("imgDelete", {//               del: delUrl,//              tempFilePaths: this.uploadLists//           });//       } else if (res.cancel) {}//     }// });},imgPreview(index) {var imgData = []this.uploadLists.forEach(item => {if (!this.isVideo(item)) {imgData.push(this.getFileUrl(item))}})//console.log('imgPreview', imgData)uni.previewImage({urls: imgData,current: index,loop: true,});},chooseFile() {if (this.disabled) {return false;}switch (this.mediaTypeData.indexOf(this.mediaType)) {case 1: //视频this.videoAdd();break;case 2: //全部uni.showActionSheet({itemList: ['相册', '视频'],success: (res) => {if (res.tapIndex == 1) {this.videoAdd();} else if (res.tapIndex == 0) {this.imgAdd();}},fail: (res) => {console.log(res.errMsg);}});break;default: //图片this.imgAdd();break;}//if(this.mediaType=='image'){},videoAdd() {//console.log('videoAdd')let nowNum = Math.abs(this.uploadLists.length - this.max);let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量uni.chooseVideo({compressed: this.compress,sourceType: this.sourceType,camera: this.camera,maxDuration: this.maxDuration,success: (res) => {// console.log('videoAdd', res)// console.log(res.tempFilePath)this.chooseSuccessMethod([res.tempFilePath], 1)//this.imgUpload([res.tempFilePath]);//console.log('tempFiles', res)// if (this.action == '') { //未配置上传路径//   this.$emit("chooseSuccess", res.tempFilePaths);// } else {//  if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传//        this.imgCompress(res.tempFilePaths);//  } else {//      this.imgUpload(res.tempFilePaths);//    }// }}});},imgAdd() {//console.log('imgAdd')let nowNum = Math.abs(this.uploadLists.length - this.max);let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量//console.log('nowNum', nowNum)//console.log('thisNum', thisNum)// #ifdef APP-PLUSif (this.sourceType.length > 1) {uni.showActionSheet({itemList: ['拍摄', '从手机相册选择'],success: (res) => {if (res.tapIndex == 1) {this.appGallery(thisNum);} else if (res.tapIndex == 0) {this.appCamera();}},fail: (res) => {console.log(res.errMsg);}});}if (this.sourceType.length == 1 && this.sourceType.indexOf('album') > -1) {this.appGallery(thisNum);}if (this.sourceType.length == 1 && this.sourceType.indexOf('camera') > -1) {this.appCamera();}// #endif//#ifndef APP-PLUSuni.chooseImage({count: thisNum,sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有sourceType: this.sourceType,success: (res) => {this.chooseSuccessMethod(res.tempFilePaths, 0)//console.log('tempFiles', res)// if (this.action == '') { //未配置上传路径//     this.$emit("chooseSuccess", res.tempFilePaths);// } else {//  if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M,进行压缩上传//        this.imgCompress(res.tempFilePaths);//  } else {//      this.imgUpload(res.tempFilePaths);//    }// }}});// #endif},appCamera() {var cmr = plus.camera.getCamera();var res = cmr.supportedImageResolutions[0];var fmt = cmr.supportedImageFormats[0];//console.log("Resolution: " + res + ", Format: " + fmt);cmr.captureImage((path) => {//alert("Capture image success: " + path);this.chooseSuccessMethod([path], 0)},(error) => {//alert("Capture image failed: " + error.message);console.log("Capture image failed: " + error.message)}, {resolution: res,format: fmt});},appGallery(maxNum) {plus.gallery.pick((res) => {this.chooseSuccessMethod(res.files, 0)}, function(e) {//console.log("取消选择图片");}, {filter: "image",multiple: true,maximum: maxNum});},chooseSuccessMethod(filePaths, type) {if (this.action == '') { //未配置上传路径this.$emit("chooseSuccess", filePaths, type); //filePaths 路径 type 0 为图片 1为视频} else {if (type == 1) {this.imgUpload(filePaths, type);} else {if (this.compress) { //设置了需要压缩this.imgCompress(filePaths, type);} else {this.imgUpload(filePaths, type);}}}},imgCompress(tempFilePaths, type) { //type 0 为图片 1为视频uni.showLoading({title: '压缩中...'});let compressImgs = [];let results = [];tempFilePaths.forEach((item, index) => {compressImgs.push(new Promise((resolve, reject) => {// #ifndef H5uni.compressImage({src: item,quality: this.quality,success: res => {//console.log('compressImage', res.tempFilePath)results.push(res.tempFilePath);resolve(res.tempFilePath);},fail: (err) => {//console.log(err.errMsg);reject(err);},complete: () => {//uni.hideLoading();}})// #endif// #ifdef H5this.canvasDataURL(item, {quality: this.quality / 100}, (base64Codes) => {//this.imgUpload(base64Codes);results.push(base64Codes);resolve(base64Codes);})// #endif}))})Promise.all(compressImgs) //执行所有需请求的接口.then((results) => {uni.hideLoading();//console.log('imgCompress', type)this.imgUpload(results, type);}).catch((res, object) => {uni.hideLoading();});},imgUpload(tempFilePaths, type) { //type 0 为图片 1为视频// if (this.action == '') {//    uni.showToast({//       title: '未配置上传地址',//       icon: 'none',//       duration: 2000//    });//   return false;// }if (this.action == 'uniCloud') {this.uniCloudUpload(tempFilePaths, type)return}uni.showLoading({title: '上传中'});//console.log('imgUpload', tempFilePaths)let uploadImgs = [];tempFilePaths.forEach((item, index) => {uploadImgs.push(new Promise((resolve, reject) => {//console.log(index, item)const uploadTask = uni.uploadFile({url: this.action, //仅为示例,非真实的接口地址filePath: item,name: this.name,fileType: 'image',formData: this.formData,header: this.headers,success: (uploadFileRes) => {//uni.hideLoading();//console.log(typeof this.uploadSuccess)//console.log('')uploadFileRes.fileType = typeif (typeof this.uploadSuccess == 'function') {let thisUploadSuccess = this.uploadSuccess(uploadFileRes)if (thisUploadSuccess.success) {if (this.dataType == 0) {this.value.push(thisUploadSuccess.url)} else {this.value.push({type: type,url: thisUploadSuccess.url})}this.$emit("input", this.uploadLists);}}resolve(uploadFileRes);this.$emit("uploadSuccess", uploadFileRes);},fail: (err) => {console.log(err);//uni.hideLoading();reject(err);this.$emit("uploadFail", err);},complete: () => {//uni.hideLoading();}});}))})Promise.all(uploadImgs) //执行所有需请求的接口.then((results) => {uni.hideLoading();}).catch((res, object) => {uni.hideLoading();this.$emit("uploadFail", res);});// uploadTask.onProgressUpdate((res) => {//    //console.log('',)//  uni.showLoading({//         title: '上传中' + res.progress + '%'//   });//   if (res.progress == 100) {//      uni.hideLoading();//    }// });},uniCloudUpload(tempFilePaths, type) {uni.showLoading({title: '上传中'});console.log('uniCloudUpload', tempFilePaths);let uploadImgs = [];tempFilePaths.forEach((item, index) => {uploadImgs.push(new Promise((resolve, reject) => {uniCloud.uploadFile({filePath: item,cloudPath: this.guid() + '.' + this.getFileType(item, type),success(uploadFileRes) {if (uploadFileRes.success) {resolve(uploadFileRes.fileID);}},fail(err) {console.log(err);reject(err);},complete() {}});}))})Promise.all(uploadImgs) //执行所有需请求的接口.then((results) => {uni.hideLoading();// console.log('then', results)uniCloud.getTempFileURL({fileList: results,success: (res) => {//console.log('success',res.fileList)res.fileList.forEach(item => {//console.log(item.tempFileURL)this.value.push(item.tempFileURL)})},fail() {},complete() {}});}).catch((res, object) => {uni.hideLoading();});},getFileType(path, type) { //手机端默认图片为jpg 视频为mp4// #ifdef H5 var result = type == 0 ? 'jpg' : 'mp4';// #endif// #ifndef H5var result = path.split('.').pop().toLowerCase();// #ifdef MP if (this.compress) {//微信小程序压缩完没有后缀result = type == 0 ? 'jpg' : 'mp4';}// #endif// #endifreturn result;},guid() {return 'xxxxxxxx-date-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random() * 16 | 0,v = c == 'x' ? r : (r & 0x3 | 0x8);return v.toString(16);}).replace(/date/g, function(c) {return Date.parse(new Date());});},canvasDataURL(path, obj, callback) {var img = new Image();img.src = path;img.onload = function() {var that = this;// 默认按比例压缩var w = that.width,h = that.height,scale = w / h;w = obj.width || w;h = obj.height || (w / scale);var quality = 0.8; // 默认图片质量为0.8//生成canvasvar canvas = document.createElement('canvas');var ctx = canvas.getContext('2d');// 创建属性节点var anw = document.createAttribute("width");anw.nodeValue = w;var anh = document.createAttribute("height");anh.nodeValue = h;canvas.setAttributeNode(anw);canvas.setAttributeNode(anh);ctx.drawImage(that, 0, 0, w, h);// 图像质量if (obj.quality && obj.quality <= 1 && obj.quality > 0) {quality = obj.quality;}// quality值越小,所绘制出的图像越模糊var base64 = canvas.toDataURL('image/jpeg', quality);// 回调函数返回base64的值callback(base64);}},}}
</script><style>.preview-full {position: fixed;top: 0;left: 0;bottom: 0;width: 100%;height: 100%;z-index: 1002;}.preview-full video {width: 100%;height: 100%;z-index: 1002;}.preview-full-close {position: fixed;right: 32rpx;top: 125rpx;width: 80rpx;height: 80rpx;line-height: 60rpx;text-align: center;z-index: 1003;/*    background-color: #808080; */color: #fff;font-size: 65rpx;font-weight: bold;text-shadow: 1px 2px 5px rgb(0 0 0);}/* .preview-full-close-before,.preview-full-close-after {position: absolute;top: 50%;left: 50%;content: '';height: 60rpx;margin-top: -30rpx;width: 6rpx;margin-left: -3rpx;background-color: #FFFFFF;z-index: 20000;}.preview-full-close-before {transform: rotate(45deg);}.preview-full-close-after {transform: rotate(-45deg);} */.htz-image-upload-list {display: flex;flex-wrap: wrap;}.htz-image-upload-Item {width: 160rpx;height: 160rpx;/* margin: 13rpx; *//* border-radius: 4rpx; */position: relative;}.htz-image-upload-Item image {width: 100%;height: 100%;border-radius: 10rpx;}.htz-image-upload-Item-video {width: 100%;height: 100%;/* border-radius: 10rpx; */position: relative;}.htz-image-upload-Item-video-fixed {position: absolute;top: 0;left: 0;bottom: 0;width: 100%;height: 100%;/* border-radius: 10rpx; */z-index: 996;}.htz-image-upload-Item video {width: 100%;height: 100%;/* border-radius: 10rpx; */}.htz-image-upload-Item-add {font-size: 105rpx;/* line-height: 160rpx; */text-align: center;border: 2px solid #979797;background: #d8d8d8;color: #d9d9d9;position: relative;margin: 0 8px 8px 0;box-sizing: border-box;border-radius: 2px;}.videobox{/* position: absolute; */}.u-icon{display: inline-block;   position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);white-space: nowrap;color: #979797;}.htz-image-upload-Item-del {background-color: #373737;font-size: 24rpx;/* padding-left: 10rpx;box-sizing: border-box; */position: absolute;width: 28rpx;height: 28rpx;line-height: 19rpx;text-align: center;top: 0;right: 0;z-index: 997;color: #fff;/* border-bottom-left-radius: 100px; */border-radius: 0px 50px 0px 100px;}.htz-image-upload-Item-del-cover {background-color: #272727;font-size: 24rpx;position: absolute;width: 28rpx;height: 28rpx;text-align: center;top: 0;right: 0;color: #fff;/* #ifdef APP-PLUS */line-height: 19rpx;/* #endif *//* #ifndef APP-PLUS *//* line-height: 35rpx; *//* #endif */z-index: 997;border-radius: 0px 50px 0px 100px;}.htz-image-upload-Item-video-app-poster {width: 100%;height: 100%;}
</style>

uniapp上传图片视频插架分享相关推荐

  1. uniapp上传图片和视频到OSS

    1.首先需要拿到formData里面的参数如下所示: formData: {name: nameStr,key: nameStr,policy: 'xxxxxxxxx', // 输入你获取的的poli ...

  2. 【uniapp】微信小程序中的视频下载和分享、PDF下载和分享、完整下载(图片、视频、各种文件)

    目录 一.视频的下载 二.视频的分享 三.PDF下载和分享 四.完整 五.有可能是坑 一.视频的下载 先使用uni.downloadFile将文件下载到将远程文件下载到小程序内存中,然后使用uni.s ...

  3. 【uniapp】视频分享预览小程序

    六一收到个不同以往的需求,我的指导老师最近有点忙,让我们帮忙做一个可以通过二维码预览视频的小程序 收到需求后,因为只是临时用一下,不打算写一套完整的系统,所以大概的思路就是,其他成员将视频通过ftp传 ...

  4. 干货 | 视频插帧的方案实现与对比~~

    对于视频网站.电视厂商以及进行视频压制的用户来说,改变视频的帧率算是一个比较常见的需求. 视频网站改变帧率主要是为了向不同级别的网站用户提供差异化服务:电视厂商则是以提供更好的显示效果作为电视的卖点: ...

  5. 丝滑!CVPR 2021 视频插帧论文+开源代码汇总

    点击上方"AI算法与图像处理",选择加"星标"或"置顶"重磅干货,第一时间送达 从事算法岗经常需要查看最新的研究成果,希望从中能借鉴一些别人 ...

  6. 截至2022.2.1全网最全面最开放的蓝牙AOA高精度定位行业生态解决方案配套产品及商用案例真实视频合集分享来自深圳核芯物联科技

    截至2022.2.1全网最全面最开放的蓝牙AOA高精度定位行业生态解决方案配套产品及商用案例真实视频合集分享来自深圳核芯物联科技 原创 核芯物联岳毅恒 国产蓝牙AOA高精度定位岳毅恒 2022-01- ...

  7. 干货!考虑部署在移动端的视频插帧模型:CDFI

    点击蓝字 关注我们 AI TIME欢迎每一位AI爱好者的加入! 对于给定的视频进行插帧操作提高帧率会使得视频更加流畅,但往往用于视频插帧的深度神经网络都具有复杂的模型架构,这使得它们无法部署在系统资源 ...

  8. CVPR 2023 | EMA-VFI: 基于帧间注意力提取运动和外观信息的高效视频插帧

    ©作者 | Guozhen Zhang 单位 | 南京大学媒体计算组 本文介绍南京大学媒体计算组最近被 CVPR 2023 接收的视频插帧方向的工作:Extracting Motion and App ...

  9. PPT怎么插入视频?3个视频插入方法分享!

    Anna是个初入职场的新人,最近要进行工作汇报,需要制作PPT并插入相关的讲解视频.但她对PPT的运用不熟悉,不知道应该如何操作!特此来询问应该如何在PPT中插入视频? 在演示文稿中插入视频可以使PP ...

  10. vue 上传图片视频组件,可拍照选择照片,解决苹果手机拍照旋转问题

    vue 上传图片视频组件,可拍照选择照片,解决苹果手机拍照旋转问题 参考文章: (1)vue 上传图片视频组件,可拍照选择照片,解决苹果手机拍照旋转问题 (2)https://www.cnblogs. ...

最新文章

  1. 一个牛逼的 多级缓存 实现方案!
  2. tableview 展开
  3. PLSQL不能选择数据库问题
  4. 京东 你访问的页面需要验证证书_SSL证书安全认证有什么原理?
  5. html option ajax,Ajax实现简单下拉选项效果【推荐】
  6. 工作任务:解决双主控倒换时双机切换问题
  7. mysql的dockerfile_dockerfile构建mysql镜像
  8. UITextfield键盘相关设置
  9. 手机如何看python文件大小_如何安全地检查上传文件的大小?(How to check size of uploaded file safely in bottlepy?)...
  10. Linux:Linux下进程间通信方式的学习
  11. Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's ro
  12. [515]歌曲识别-dejavu-python
  13. 看山不是山看水不是水
  14. unfinished application
  15. Android根据输入法的状态隐藏和关闭输入法
  16. (一)微信小程序支付前后台
  17. PSIM仿真+C语言(c block)实现PID控制和最小拍控制
  18. CEST日期格式转换为 年月日时分秒
  19. Elasticsearch权限控制
  20. 正则表达式匹配USD格式

热门文章

  1. java net php_atitit. web 在线文件管理器最佳实践(1)--- elFinder 的使用流程解决之道 。打开浏览服务器文件夹java .net php...
  2. excel高级筛选怎么用_Excel 筛选之“高级筛选”(绝对不可错过的强大工具)
  3. xxx.com和www.xxx.com的区别
  4. Windows Server 2012 R2 安装 Docker
  5. python下载图片到文件夹_Python批量下载网页图片详细教程
  6. 房价――你欠中国老百姓一次彻底的崩盘!
  7. jenkins 使用报ERROR: svn: E155010: The node ‘/aaa/bbb/ccc/ddd‘ was not found.
  8. java对象的封装继承和多肽_java零基础入门第七天 继承 多肽 重写 重载
  9. java弹弹球实验报告_Java程序设计实验报告2(弹球游戏)1
  10. 权限管理大升级,开源智能客服系统春松客服 v6 版本发布 | Chatopera