鸿蒙图片上传功能

一.获取相册图片

最大长度为3   用户选择的时候需要处理当前显示的img数组

// 选择相册图片
  async doPickPhoto() {
    let PhotoSelectOptions = new picker.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 3;
    let photoPicker = new picker.PhotoViewPicker();
    let res = await photoPicker.select(PhotoSelectOptions)
    // 获取当前相册和用户选取的相册长度,最多只能上传3张
    const length = this.photoList.length+res.photoUris.length
    // 多出来的话进行前删,多几个删几个
    if(length>3){
      this.photoList.splice(0, length - 3);
    }
    //不直接进行赋值是因为会清空之前的
    res.photoUris.forEach((item:string)=>{
      this.photoList.push(item)
    })
  }

二.转为base64因为后端接口需要是base64格式,不需要的话可以直接使用photoList

base64Transition=()=>{
    this.submitImgList=[]
    this.photoList.forEach((item:string)=>{
        const file = fs.openSync(item)
        // 2.3 同步获取文件的详细信息
        const stat = fs.statSync(file.fd)
      // 2.4 创建缓冲区存储读取的文件流
        const buffer = new ArrayBuffer(stat.size)
        const num = fs.readSync(file.fd, buffer)
      // 2.5 开始同步读取文件流到缓冲区
        fs.readSync(file.fd, buffer)
      // 3. 转成base64编码的字符串
        const helper = new util.Base64Helper()
        const imgList= helper.encodeToStringSync(new Uint8Array(buffer))
        this.submitImgList.push({'image':imgList})
    })
  }

三.页面布局及使用

因为最大限制为3张,所以等于大于3的话会隐藏上传按钮,还有删除功能

  Row(){
            Text('上传图片').textLeftStyle().margin({right:10})
            ForEach(this.photoList,(item:string,index:number)=>{
              Stack({ alignContent: Alignment.TopEnd }) {
                // 图片
                Image(item)
                  .width(70).height(70).margin(10)
                Image($r('app.media.ic_btn_delete')).width(30).height(30)
                  .onClick(() => {
                    // 删除
                    this.photoList.splice(index, 1)
                  })
              }
            })
            // 添加
            Image($r("app.media.add")).onClick(async ()=>{
             await this.doPickPhoto()
            }).visibility(this.photoList.length>=3 ?Visibility.None:Visibility.Visible)
              .width(70).height(70)
          }.width('100%').padding(5)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值