微信小程序上传附件

上传文件及图片 下载,预览、删除

自定义封装组件 哪儿用哪儿调用即可

wxml代码
<!-- <view>上传文件(我是子组件)</view> -->
<view class="fileImgAll"><view class="imginfo"style="border-bottom:{{attachmentImgFile&&attachmentImgFile.length!==0?'1px dashed #999':''}};display: {{fileDetail?'none':'block'}};"><!-- 点击上传文件按钮 --><view bindtap="uploadAction" class="fileLeft"><i class="iconfont icon-weixin" style="color: rgb(13, 175, 75); font-size: larger;"></i>上传文件</view><!-- 点击上传图片按钮 --><view bindtap="uploadup" class="fileRight"><i class="iconfont .icon-xiangce" style="color: rgb(148, 24, 206);  font-size: larger;"></i>上传图片</view></view><view class="allStyle"><!-- 图片  文件  渲染  展示 --><!-- 单据 展示 根据 渲染 数组的不同 --><view wx:if="{{orderShowUp.id&&orderAttachment==='order_attachment'}}" wx:for="{{orderShowUp.attachment}}"wx:key="index" class="fileImg"><!-- 上传文件在此处渲染 --><view class="fileAll" wx:if="{{item.mime_type!=='image/'+item.extension}}"><i bindtap="uploadDown" data-index="{{index}}" class="iconfont .icon-wenjian1"style="color: rgb(14 153 234);  font-size: x-large;"></i><i wx:if="{{fileDetail===false}}" bindtap="setDelArr" class='fileTips' data-index="{{index}}">X</i></view><!-- 如果上传相册是 gif类型 或者后台没返回 thumb文件流  在此处展示文件样式 但点击下载后 可直接预览--><view class="fileAll" wx:if="{{item.mime_type==='image/'+item.extension&&!item.thumb}}"><i bindtap="listenerButtonPreviewImage" data-index="{{index}}" class="iconfont .icon-wenjian1"style="color: rgb(14 153 234);  font-size: x-large;"></i><!-- <i wx:if="{{fileDetail===false}}" bindtap="setDelArr" class='fileTips' data-index="{{index}}">X</i> --></view><!-- 上传图片 在此处渲染 --><view class="imgStyle" wx:if="{{item.mime_type==='image/'+item.extension}}"><block><image mode='aspectFit' src="data:image/png;base64,{{item.thumb}}"bindtap="listenerButtonPreviewImage" style="width: 100%;height: 100%;  border-radius: 10%;"data-index="{{index}}" /><i wx:if="{{fileDetail===false}}" bindtap="setDelArr" class='fileTips' data-index="{{index}}">X</i></block></view></view></view>
</view>
js 代码
// components/uploaddown/index.js
const app = getApp()
Component({/*** 组件的属性列表*/properties: {count: { // 最多选择图片的张数type: Number,value: 9,},thumb: {type: Boolean,value: ''},orderShow: {type: Object,},attachment: {type: Array,},orderAttachment: {type: String,},fileDetail: {type: Boolean,}},/*** 组件的初始数据*/data: {fileList: [], // 需要上传的图片列表isAct: false,isSava: false,files: [],loading: false,storeList: [],imgModalBox: {visible: false,previewImage: '',imgWidth: 0,imgHeight: 0,original: false, // 查看原图},tempFilePaths: [], // 上传的附件 图片storeName: '', // 下载时需要传给路由的文件字段deleteFilePathName: '', // 获取删除图片路径名tempUnImgList: [], // 上传的文件列表itemFilePathName: '', // 获取上传时文件路径名itemFileUrlName: '', // 获取上传后 后端返回的文件路径名fileNamePath: '', // 截取数组的pathfileData: [], // 上传文件后获取返回的结果  文件markFile: '', // 删除文件按钮  文件// deleFileList: [], // 删除时传给后台数组  文件allImgList: [],imageShow: false, // 图片上传完成是  渲染图片filesShow: false, // 文件上传成功后显示orderShowUp: {},titleImg: '',attachmentImgFile: [], // 区分单据和病例detailUrl: '',},attached() {const {orderShow,orderAttachment,fileDetail,} = this.properties;this.setData({orderShowUp: orderShow,})if (orderAttachment === "order_attachment") {this.setData({attachmentImgFile: orderShow.attachment})} else if (orderAttachment === "order_patient_attachment") {this.setData({attachmentImgFile: orderShow.patient_attachment})} else {this.setData({attachmentImgFile: orderShow.attachment})}},/*** 组件的方法列表*/methods: {uploadAction(e) { // 支持聊天界面上传 文件const {orderAttachment,} = this.properties;const that = this;const {orderShowUp} = that.data;wx.chooseMessageFile({count: 9,type: 'file',success(res) {wx.showToast({ // 显示消息提示框title: '正在上传...',icon: 'loading',mask: true,duration: 1000})const tempFilePaths = res.tempFilesthat.setData({tempUnImgList: res.tempFiles // 传给后台数据数组})var arr = [];const Token = wx.getStorageSync("token");let count = tempFilePaths.length;for (let i = 0; i < tempFilePaths.length; i++) {const element = tempFilePaths[i];wx.uploadFile({url: `${app.host}attachments`,filePath: tempFilePaths[i].path,name: 'files[]',header: {'Content-Type': 'application/json',token: `${Token}`},formData: {'from_id': orderShowUp.id,'from_field': orderAttachment,'files[]': res.tempFiles,},// formData: {//     'from_id': 28036,//     'from_field': 'order_attachment',//     'files[]': res.tempFiles,// },success(res) {if (orderAttachment === 'logistics_attachment') {app.request({method: "GET",url: `logistics/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data,attachmentImgFile: res.data.data.attachment})}).catch(err => {})} else {app.request({method: "GET",url: `tumor/order/orders/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data})if (orderAttachment === "order_attachment") {that.setData({attachmentImgFile: res.data.data.attachment})} else {that.setData({attachmentImgFile: res.data.data.patient_attachment})}}).catch(err => {})}that.setData({filesShow: true // 文件上传成功后显示})const strData = res.data //返回的结果var fileDataList = JSON.parse(strData).data;if (JSON.parse(strData).code !== 0) {wx.showToast({title: '文件格式不正确(jpeg,gif,png,pdf,doc,docx,xls,xlsx,ppt,pptx)',content: '上传图片失败',showCancel: false,success: function (res) {}})}for (let j = 0; j < fileDataList.length; j++) {const fileArray = fileDataList;const item = fileArray[j];that.setData({storeName: item.store_name,})for (let k = 0; k < that.data.tempUnImgList.length; k++) {const itemFileIndex = that.data.tempUnImgList[k];const itemFilePathName = itemFileIndex.path.slice(11);that.setData({itemFilePathName, // 上传前传给服务器的文件 截取后的路径名itemFileUrlName: item.original_name, // 服务器返回的文件路径名})}if (item.id) {// 添加缓存数据wx.setStorageSync('list_file', fileDataList[0])var valueFile = wx.getStorageSync('list_file');arr.push(valueFile)that.setData({fileData: arr})if (count === 1) {wx.showToast({title: '上传成功',icon: '',mask: true,duration: 1300})} else {count -= 1;}} else {console.log("有点问题");}}},fail: function (res) {wx.showToast({title: '上传失败',icon: '',mask: true,duration: 1300})}})}}})},/** * 上传附件  支持本地图库上传* */uploadup: function (e) {if (this.data.thumb === false) {this.setData({thumb: true})}const {orderAttachment,} = this.properties;let that = this;const {orderShowUp} = that.data;wx.chooseImage({count: that.data.count,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success(res) {// tempFilePath可以作为img标签的src属性显示图片const tempFilePaths = res.tempFilePaths;// wx.showToast({ // 显示消息提示框//     title: '正在上传...',//     icon: 'loading',//     mask: true,//     duration: 1000// })wx.showLoading({title: '正在上传',})that.setData({tempFilePaths: tempFilePaths})let count = that.data.tempFilePaths.length;var arr = [];for (var j = 0; j < that.data.tempFilePaths.length; j++) {const Token = wx.getStorageSync("token");wx.uploadFile({url: `${app.host}attachments`,filePath: tempFilePaths[j],name: 'files[]',header: {'Content-Type': 'application/json',token: `${Token}`},formData: {'from_id': orderShowUp.id,'from_field': orderAttachment,'files[]': res.tempFiles,},// formData: {//     'from_id': 28036,//     'from_field': 'order_attachment',//     'files[]': tempFilePaths,// },success(res) {if (orderAttachment === 'logistics_attachment') {app.request({method: "GET",url: `logistics/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data,attachmentImgFile: res.data.data.attachment})}).catch(err => {})} else {app.request({method: "GET",url: `tumor/order/orders/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data})if (orderAttachment === "order_attachment") {that.setData({attachmentImgFile: res.data.data.attachment})} else if (orderAttachment === "order_patient_attachment") {that.setData({attachmentImgFile: res.data.data.patient_attachment})}}).catch(err => {})}that.setData({imageShow: true // 图片上传完成是  渲染图片})//如果是最后一张,则隐藏等待中 // if (count == tempFilePaths.length) {//     wx.hideToast();// }const str = res.data //返回的结果var pic = JSON.parse(str);if (count === 1) {wx.hideLoading()if (JSON.parse(str).code === 0) {wx.showToast({title: '上传成功',icon: '',mask: true,duration: 1300})} else {wx.showToast({title: '文件格式不正确',content: '上传图片失败',showCancel: false,success: function (res) {}})}} else {count -= 1;}// 添加缓存数据wx.setStorageSync('list_stutas', pic.data[0])var valueFile = wx.getStorageSync('list_stutas');arr.push(valueFile)that.setData({fileList: arr})},fail: function (res) {wx.showToast({title: '错误提示',content: '上传图片失败',showCancel: false,success: function (res) {}})}})}}})},/** * 预览上传的文件*/listenerButtonPreviewImage: function (e) {// this.triggerEvent("submit", this.data.tempFilePaths)  // 子传父let index = e.target.dataset.index;let that = this;const {orderAttachment} = that.data;if (orderAttachment === "order_attachment") {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})} else if (orderAttachment === "order_patient_attachment") {const patient_attachment = that.data.orderShowUp.patient_attachment;that.setData({attachmentImgFile: patient_attachment})} else {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})}const Token = wx.getStorageSync("token");wx.showLoading({ // loading加载title: '加载中',})wx.downloadFile({url: `${app.host}attachments/${that.data.attachmentImgFile[index].store_name}/download`, //仅为示例,并非真实的资源// url:`${app.host}sales/attachments`,// filePath: tempFilePaths[i].path,header: {'Content-Type': 'application/json',token: `${Token}`},success(res) {const arr = [];const tempFilePath = res.tempFilePath;arr.push(tempFilePath);wx.previewImage({ // 在新页面中全屏预览图片// current: that.data.tempFilePaths[index], // 当前显示图片的http链接// urls: that.data.tempFilePaths, // 需要预览的图片http链接列表current: tempFilePath, // 当前显示图片的http链接urls: arr, // 需要预览的图片http链接列表success: function (res) {wx.hideLoading()},fail: function (res) {wx.showToast({title: '预览失败',icon: '',mask: true,duration: 1300})}})}})},/** * 点击文件下载*/uploadDown: function (e) {const that = this;that.setData({markFile: e.currentTarget.dataset.index})const deleteImgIndex = this.data.markFile; // 获取定位的文件indexwx.getSavedFileList({ // 获取文件列表success(res) {res.fileList.forEach((val, key) => { // 遍历文件列表里的数据// 删除存储的垃圾数据wx.removeSavedFile({filePath: val.filePath,})})}})wx.showToast({ // 显示消息提示框title: '正在下载...',icon: 'loading',mask: true,duration: 1000})// const storeName = this.data.storeName;const {orderAttachment} = that.data;if (orderAttachment === "order_attachment") {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})} else if (orderAttachment === "order_patient_attachment") {const attachment = that.data.orderShowUp.patient_attachment;that.setData({attachmentImgFile: attachment})} else {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})}const Token = wx.getStorageSync("token");wx.downloadFile({url: `${app.host}attachments/${that.data.attachmentImgFile[deleteImgIndex].store_name}/download`, //仅为示例,并非真实的资源// url:`${app.host}sales/attachments`,// filePath: tempFilePaths[i].path,header: {'Content-Type': 'application/json',token: `${Token}`},success(res) {wx.showToast({title: '下载成功',icon: '',mask: true,duration: 1300})const tempFilePath = res.tempFilePath;// 保存文件wx.saveFile({tempFilePath,success: function (res) {const savedFilePath = res.savedFilePath;// 打开文件wx.openDocument({filePath: savedFilePath,success: function (res) {console.log('打开文档成功')},});},fail: function (err) {console.log('保存失败:', err)}});// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容if (res.statusCode === 200) {// wx.playVoice({//     filePath: res.tempFilePath// })wx.showToast({title: '下载成功',icon: '',mask: true,duration: 1500})}},fail: function (err) {console.log('下载失败:', err);},})},/** * 删除当前文件 或者图片*/setDelArr: function (file) {const that = this;that.setData({markFile: file.currentTarget.dataset.index})const {orderShowUp} = that.data;const deleteImgIndex = this.data.markFile; // 获取定位的文件indexconst deleFileList = that.data.tempUnImgList; // 获取上传时传给后端的listconst fileList = that.data.fileData; // 获取上传时后端传来的文件const {orderAttachment} = that.data;if (orderAttachment === "order_attachment") {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})} else if (orderAttachment === "order_patient_attachment") {const patient_attachment = that.data.orderShowUp.patient_attachment;that.setData({attachmentImgFile: patient_attachment})} else {const attachment = that.data.orderShowUp.attachment;that.setData({attachmentImgFile: attachment})}wx.showModal({title: '确认删除',content: '你确定要删除吗?',success: res => {if (res.confirm) {wx.showToast({ // 显示消息提示框title: '正在删除...',icon: 'loading',mask: true,duration: 1000})const Token = wx.getStorageSync("token");// if (fileList[0].name === element.path.slice(11)) { // pc端使用// if (element.path.slice(11) === attachment[deleteImgIndex].original_name) { // pc端使用app.request({url: `attachments/${that.data.attachmentImgFile[deleteImgIndex].store_name}/delete`,method: 'POST', // 判断请求类型,除了值等于'post'外,其余值均视作getdata: {from_id: orderShowUp.id,from_field: orderAttachment,},header: {'Content-Type': 'application/json',token: `${Token}`},}).then(res => {if (orderAttachment === 'logistics_attachment') {app.request({method: "GET",url: `logistics/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data})if (res.data.data.attachment.length === 0) {that.setData({attachmentImgFile: []})}}).catch(err => {})} else {app.request({method: "GET",url: `tumor/order/orders/${orderShowUp.id}`,}).then(res => {that.setData({orderShowUp: res.data.data})if (orderAttachment === "order_attachment" && !res.data.data.attachment) {that.setData({attachmentImgFile: []})} else if (!res.data.data.patient_attachment) {that.setData({attachmentImgFile: []})}}).catch(err => {})}wx.showToast({title: '删除成功',icon: '',mask: true,duration: 1300})// newFiles = newFiles.filter(item => item.original_name !== deleFileList[deleteImgIndex].path.slice(11));})// } // }}}})},},
})
CSS 代码
/* components/uploaddown/index.wxss */
@import "../../app.wxss";
@import "../../pages/order/order_search/logistics/SendSamples/index.wxss";@media (max-width: 767px) {/* .imginfo {width: 324px;height: 50px;flex-direction: column;align-items: center;} */.allStyle {width: 324px;/* background-color: rosybrown; */float: left;}
}.fileImgAll {width: 100%;height: 100%;overflow: hidden;padding-left: 5rpx;/* background-color: thistle; */
}.imginfo {/* width: 715rpx; */width: 100%;height: 79rpx;align-items: center;/* border-bottom: 1px dashed #999; */padding-bottom: 4rpx;margin-bottom: 5rpx;display: flex;overflow: hidden;
}.fileLeft {float: left;width: 49%;text-align: center;border-right: 1px dashed #999;flex: 1;
}.fileRight {float: right;width: 49%;text-align: center;flex: 1;
}/* 渲染文件 及 图片   ================= */
.allStyle {width: 100%;height: 100%;/* background-color: rosybrown; *//* padding-bottom: 8rpx; */padding-top: 28rpx;padding-left: 7rpx;text-align: left;/* float: left; *//* margin-top: 16rpx; *//* display: inline; *//* display: flex; *//* position: relative; */
}.fileImg {width: 18%;height: 120rpx;border-radius: 10%;display: inline-block;overflow: hidden;margin-right: 7rpx;border: 1px solid #d9d9d9;text-align: center;position: relative;
}/* 文件渲染    ================ 开始 */
.fileAll {/* position: absolute; */width: 100%;height: 100%;/* width: 18%;height: 120rpx; */border-radius: 10%;overflow: hidden;display: inline-block;/* flex: 1; */background-color: #fff;margin-right: 7rpx;text-align: center;/* padding: 43rpx; *//* padding: 13rpx; *//* position: relative; */padding-top: 9rpx;
}.fileStyle {width: 25%;height: 25%;/* display: flex; */background-color: plum;
}.fileTips {width: 40%;height: 40%;margin-left: 20rpx;/* background-color: rgb(83, 19, 136); */font-size: 31rpx;position: absolute;top: -33rpx;left: 68rpx;z-index: 999;color: #666666ab;
}/* 文件     渲染    ================ 结束 *//* 图片     渲染    ================ 开始 */
.imgStyle {display: inline-block;width: 83%;height: 79%;/* width: 18%;height: 120rpx; *//* margin-right: 7rpx; */border-radius: 10%;overflow: hidden;/* background-color: plum; *//* border: 1px solid rebeccapurple; */margin-top: 14rpx;/* margin-top: 20rpx; *//* flex: 1; *//* background-color: lightskyblue; */
}/* 删除图片 */
.tips {position: absolute;top: -32rpx;right: 9rpx;color: #666;width: 20rpx;height: 20rpx;/* background-color: mediumslateblue; */font-size: 31rpx;padding-bottom: 20rpx;z-index: 600rpx;margin-left: -25rpx;
}/* 图片     渲染    ================ 开始 */
json 代码
{"component": true,"usingComponents": {"van-uploader": "@vant/weapp/uploader"}
}
如果有地方需要附件,则直接调用即可

父组件的json 里添加 准备调用的附件组件路径

{"component": true,"usingComponents": {"upload_down": "../../../../../components/uploaddown/index"}
}
这个是父组件 添加<upload_down />为封装的附件组件
  <view class="fileUp" style="padding-top: 24rpx;"><view class='upLoadClass'><view class="unloadContent"><upload_down wx:if="{{waybillShow.id}}" orderShow="{{waybillShow}}" thumb='{{thumb}}'bind:submit="submit" orderAttachment='{{"logistics_attachment"}}'></upload_down></view></view>

展示效果图

微信小程序上传图片及文件(上传、下载、删除及预览)相关推荐

  1. 微信小程序开发之文件上传下载应用场景(附Demo源码)

    微信小程序开发之文件上传下载应用场景(附Demo源码),Demo为小相册应用,源码在附件中,本示例需要腾讯云支持. http://www.henkuai.com/forum.php?mod=viewt ...

  2. 小程序 图片上传php后台,微信小程序图片选择、上传到服务器、预览(PHP)实现实例...

    微信小程序图片选择.上传到服务器.预览(php)实现实例 小程序实现选择图片.预览图片.上传到开发者服务器上 后台使用的tp3.2 图片上传 请求时候的header参考时可以去掉(个人后台验证权限使用 ...

  3. php 点击选择图片上传,微信小程序图片选择、上传到服务器、预览(PHP)实现实例...

    微信小程序图片选择.上传到服务器.预览(PHP)实现实例 小程序实现选择图片.预览图片.上传到开发者服务器上 后台使用的tp3.2 图片上传 请求时候的header参考时可以去掉(个人后台验证权限使用 ...

  4. 微信小程序+SpringBoot实现文件上传与下载

    微信小程序+SpringBoot实现文件上传与下载 1.文件上传 1.1 后端部分 1.1.1 引入Apache Commons FIleUpload组件依赖 1.1.2 设置上传文件大小限制 1.1 ...

  5. uniapp微信小程序 选择聊天记录文件上传

    目录 精简版总结 示例 容易踩的坑 1.页面刷新问题 2.extension问题 精简版总结 单文件 wx.chooseMessageFile({count: 1,//限制选择的文件数量type: ' ...

  6. 微信小程序开发之——文件上传

    一 概述 将录像的结果传递给服务器,服务端提供的接口文档为: 字段名称 字段类型 字段说明 必填项 示例 token String token 是 服务器下发的token(header) file F ...

  7. 基于Mongodb的文件上传下载,图片预览

    1.依赖 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-b ...

  8. 【微信小程序】大文件上传

  9. 微信小程序云开发-批量上传文件到云储存空间

    微信小程序开发 自己最近在玩微信小程序,准备记录一些自己遇到的,网络上没有对应教程(也许是自己没找到),或者是教程比较少的问题,然后给出自己的解决方案 目录 微信小程序开发 问题 一.云储存是什么? ...

  10. 微信小程序云开发实现上传文件和预览下载文件

    微信小程序云开发实现上传文件和预览下载文件 一.前言 目前微信提供了一个接口 wx.chooseMessageFile 它能让用户从聊天记录里面选择一个或者多个文件,然后返回它的一些信息,列入文件的p ...

最新文章

  1. python调用数据库数据类型_ajax 读取python的数据库数据类型
  2. 编写同时在PyTorch和Tensorflow上工作的代码
  3. html页面调用ico图标,如何在HTML中使用图标字体 - icon font?
  4. 聊聊自动化测试路上遇到的挑战
  5. BUTTONS V. 2.0.0——CSS按钮库
  6. Python爬虫应用实战-网站数据爬取及数据分析
  7. TCP选项:TCP_NODELAY和TCP_CORK
  8. 2018年广东工业大学文远知行杯新生程序设计竞赛 1007 活在无尽梦境的后续 β...
  9. C语言实现简单计算器(可以处理小括号)
  10. zabbix4.0 mysql本地数据库迁移到腾讯云数据库
  11. NOIP2007 T1奖学金 解题报告-S.B.S.
  12. 自定义UICollectionViewFlowLayout
  13. 程序员实用小工具(一)
  14. 轻仓的贵金属白银今日走势分析
  15. Get IT技能百科库 50个领域轻松直达
  16. 7-2 学生成绩排序 (15 分)
  17. matlab中int函数的用法
  18. Run-down Protection
  19. 班章管家:理财产品哪个好一些?从以下几个方面比较
  20. 希尔顿旗下酒店于不同城市推出餐饮外卖、连住套餐、星厨上门、户外野餐等无忧安心产品...

热门文章

  1. 【Origin】Excel连接时的日期格式问题
  2. 无限人偶服务器连接中,Pofi无限人偶
  3. linux文件名排序规则,Linux sort 排序使用详解
  4. 简单易懂百万富翁问题(漫画)
  5. igrt与imrt放疗哪个好_精确放疗为什么要选择影像引导放疗(IGRT)?
  6. 深度:大数据分析对于中国医疗保险管理的价值(N多案例分析+附下载)
  7. CVI实现简单的VISA通信软件
  8. Ubuntu16.04安装UltraEdit报错问题
  9. 电源滤波电路的种类、原理及识图技巧
  10. 如何手机扫描身份证 8.56cm 5.4cm