微信原生小程序-图片上传回显(含组件封装详解)

实现效果(如图所示):点击上传=>弹出拍摄或从手机相册中选择图片或视频=>选择图片上传=>上传成功后回显图片。

文件梳理分析(注意点):

  1. index文件表示当前页面文件,case-upload-item文件表示封装的组件文件
  2. 代码中有运用到组件传值这一知识点,基础薄弱的同学先等等,这几天我会抽时间出一个组件传值详细版,代码中已写注释,大概能看懂。
  3. 代码中的 Config.HOST 是当前项目中的浏览器地址,例如:http://www.example.com 大家在使用的时候把 Config.HOST 更换成自己项目中的地址即可
  4. 代码完整,包含布局样式和方法,可以直接拿去使用,除了第三点中的Config.HOST其它地方都不需要更改。文章最后附上代码中运用到的小程序自带方法详解
  5. 注释说明的公用方法可以放入项目中的untils内 (建议)

话不多说,直接上代码(index表当前页面文件):

  • index.wxml
<view class="case-edit-upload-container">
  <view class="case-edit-upload-btn-item-container" bind:tap="onChooseImage">
    <view class="case-edit-upload">上传申请表</view>
  </view>
  <view wx:for="{{applications}}" wx:key="index">
    <case-upload-item case-upload-item-class="case-upload-item-class" fileLableImg="{{item.labelImg}}" fileName="{{item.name}}" fileUrl="{{item.url}}" bind:onDelete="onDeleteUploadFile"/>
  </view>
</view>
  • index.wxss
.case-edit-upload-container {
  margin-bottom: 200rpx;
}

.case-edit-upload-btn-item-container {
  flex: 1;
  height: 80rpx;
  border-radius: 100rpx;
  background: #CBB486;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 32rpx;
  line-height: 36rpx;
  margin: 0rpx 20rpx;
}

.case-edit-upload {
  display: flex;
  flex-direction: row;
  align-items: center;
}
// 组件暴露的css样式
.case-upload-item-class {
  margin-top: 30rpx;
}
  • index.ts
data:{
  //先在data 中定义
  applications:[]
}
// 图片上传
onChooseImage() {
  const _this = this;
  // 弹出拍摄或从手机相册中选择图片或视频
  wx.chooseMedia({
    // 最多可以选择的文件个数
    count: 9,
    // 拍摄视频最长拍摄时间,单位秒。时间范围为 3s 至 60s 之间。不限制相册。
    maxDuration: 60,
    success(res) {
      wx.showLoading({
        title: '上传中...',
      });
      let count = 0;
      // 本地临时文件列表
      const tempFilePaths = res.tempFiles;
      if (tempFilePaths.length > 0) {
        tempFilePaths.map((item) => {
          const { tempFilePath, size } = item;
          wx.uploadFile({
            // 这里的url代表服务器地址,这里要用完整的url,/index/uploadEvidence部分不是固定的,更换成自己项目的图片接口地址
            url: `${Config.HOST}/index/uploadEvidence`,
            // 要上传文件资源的路径 (本地路径)
            filePath: tempFilePath,
            // name的值可以自定义,代表文件对应的 key
            name: 'evidence',
            success: function (res) {
              // res.data 服务器返回的数据
              const _res = JSON.parse(res.data);
              if (_res.code === 200) {
                const { applications } = _this.data;
                applications.push({
                  name: tempFilePath,
                  url: _res.data.scr || '',
                  size: `${size}`,
                  labelImg: _this.getLabelImgForUploadItem(_res.data.scr),
                })
                _this.setData({ applications });
              } else {
                wx.showToast({
                  title: '部分文件不支持上传',
                  icon: 'none'
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '文件上传失败',
                icon: 'error'
              });
            },
            complete: function () {
              count++;
              if (count === tempFilePaths.length) {
                wx.hideLoading();
              }
            }
          })
        })
      }
    }
  });
},
// 删除当前图片
onDeleteUploadFile(e) {
    const { detail: { fileUrl } } = e;
    const { applications = [] } = this.data;
    applications.map((item,index) => {
      const { url } = item;
      if (url === fileUrl) {
        applications.splice(index, 1);
        return;
      }
    });
    this.setData({ applications})
},
// 获取当前文件格式 (公用方法)
getFileSuffix(filePath: string): string{
  const index = (filePath && filePath.lastIndexOf(".")) || -1;
  const suffix = filePath && filePath.substr(index + 1);
  return suffix;
},
// 文件路径格式用于展示(公用方法)
getLabelImgForUploadItem(filePath: string): string{
  const suffix = this.getFileSuffix(filePath) || '';
  if (['doc', 'docx'].indexOf(suffix) >= 0) {
    return '/public/img/icon-word.png';
  } else if (['xls', 'xlsx'].indexOf(suffix) >= 0) {
    return '/public/img/icon-excel.png';
  } else if (['ppt', 'pptx'].indexOf(suffix) >= 0) {
    return '/public/img/icon-ppt.png';
  } else if (suffix === 'pdf') {
    return '/public/img/icon-pdf.png';
  } else if (['png', 'jpg'].indexOf(suffix) >= 0) {
    return '/public/img/icon-image.png';
  } else if (suffix === 'mp3') {
    return '/public/img/icon-audio.png';
  } else if (suffix === 'mp4') {
    return '/public/img/icon-video.png';
  }
  return '/public/img/icon-other.png';
}


  • case-upload-item.wxml (组件)
<view class="case-upload-item case-upload-item-class" data-file-url="{{fileUrl}}" bind:tap="onUploadItemClick">
  <image class="case-upload-item-img" src="{{fileLableImg}}" />
  <view class="case-upload-item-name">{{fileName}}</view>
  <!-- 这里的mp-icon需要现在全局引入具体步骤放在下面 -->
  <mp-icon class="case-upload-item-delete" icon="close" size="{{20}}" data-file-url="{{fileUrl}}" wx:if="{{showDelete}}" catchtap="onDeleteUploadItem"></mp-icon>
</view>

mp-icon的引入(官网:WeUI组件库简介 | 微信开放文档):

第一步:app.json 文件中写入:

  "useExtendedLib": {
    "weui": true
  },

第二步:在当前文件的json中引入即可,例如这里是case-upload-item.json

{
  "usingComponents": {
    "mp-icon": "weui-miniprogram/icon/icon"
  }
}

case-upload-item.wxss (组件)

.case-upload-item {
  height: 80rpx;
  border-radius: 2rpx;
  background: #fff;
  border: 1rpx solid #D9D9D9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 30rpx;
}

.case-upload-item-img {
  width: 40rpx;
  height: 48rpx;
}

.case-upload-item-delete {
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0rpx 30rpx;
}

.case-upload-item-name {
  flex: 1;
  color: #000;
  font-size: 28rpx;
  font-weight: 500;
  line-height: 44rpx;
  margin: 0rpx 24rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

case-upload-item.ts (组件)

Component({
  // 定义组件外部样式的属性, 将外部定义的 CSS 类名传递到组件内部
  externalClasses: ['case-upload-item-class'],
  properties: {
    fileLableImg: {
      type: String,
      value: '',
    },
    fileName: {
      type: String,
      value: '',
    },
    fileUrl: {
      type: String,
      value: '',
    },
    showDelete: {
      type: Boolean,
      value: true,
    }
  },
  methods: {
    // 查看当前文件或图片
    onUploadItemClick(e: any) {
      console.log('onUploadItemClick:', e)
      const { currentTarget: { dataset: { fileUrl } } } = e;
      // 获取当前图片类型
      const suffix = this.getFileSuffix(fileUrl);
      console.log('suffix:', suffix)
      if (['doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppt', 'pptx'].indexOf(suffix) >= 0) {
        wx.showLoading({
          title: '正在加载文件',
        })
        wx.downloadFile({
          // Config.HOST 代表项目中当前环境的地址,例如:https://www.baidu.com(这里是我从外部引入的,写自己项目环境即可)
          url: fileUrl.indexOf(Config.HOST) < 0 ? `${Config.HOST}${fileUrl}` : fileUrl,
          success: function (res) {
            const filePath = res.tempFilePath
            wx.openDocument({
              filePath: filePath,
              success: function (res) {
                console.log('打开文档成功:', res)
              },
              fail: function (err) {
                console.log('打开文档失败', err)
              }
            })
          },
          fail: function () {
            wx.showToast({
              title: '文件加载失败',
              duration: 2000
            });
          },
          complete: function () {
            wx.hideLoading()
          }
        });
      } else if (['png', 'jpg'].indexOf(suffix) >= 0) {
        wx.previewImage({
          current: fileUrl,
          urls: [`${Config.HOST}${fileUrl}`],
        });
      } else if (['mp4', 'mp3'].indexOf(suffix) >= 0) {
        wx.previewMedia({
          sources: [
            { url: fileUrl.indexOf(Config.HOST) < 0 ? `${Config.HOST}${fileUrl}` : fileUrl, type: 'video' }
          ],
        });
      }
    },
    //删除当前文件或图片,抛出当前url给父组件,并执行onDelete方法
    onDeleteUploadItem(e: any) {
      const { currentTarget: { dataset: { fileUrl } } } = e;
      this.triggerEvent('onDelete', { fileUrl });
    },
    // 获取当前文件类型 (公用方法)
    getFileSuffix (filePath: string): string {
      const index = (filePath && filePath.lastIndexOf(".")) || -1;
      const suffix = filePath && filePath.substr(index + 1);
      return suffix;
    }
  }
});

下面是代码中运用到的微信小程序自带方法的功能描述(附官网地址):

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序是一种基于微信平台的应用的开发模式,可以快速的开发出符合用户需求的小程序。在小程序的开发中,组件是一个非常重要的概念,通过组件可以实现复用性和模块化编程思想。 组件应用是小程序开发的基础。通过组件可以将某一模块化并封装起来,使得组件可以在不同的页面间得到复用,大大提升了开发效率并减少了代码冗余。微信小程序提供了丰富的自带组件,包括文本、图片、按钮、输入框等等,开发者也可以自己开发组件来满足自己的需求。实际开发中,通过组件可以快速搭建页面框架和业务逻辑。 Demo是一个演示小程序的示例程序。在小程序的实际开发过程中,一个好的Demo非常重要。通过Demo,开发人员可以更深入的了解小程序的开发流程、组件的应用和实际的业务开发等等。在Demo中,通常会包括小程序的一些基础操作,如页面跳转、数据绑定、组件的使用等。而在实际开发中,Demo还会包括一些复杂的业务场景,如支付、登录、数据列表展示等等。Demo不仅为开发者提供了学习和实践的机会,也方便了使用者了解该小程序的功能和特点。 总之,微信小程序组件的应用和Demo的开发都是小程序开发过程中非常重要的两个部分。良好的组件应用和精心设计的Demo,可以在极短的时间内实现小程序开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值