微信小程序中图片上传

封装了图片上传组件,支持多张上传,图片预览
代码如下:
组件调用:
index.tsx

<UploadPic
  maxNumber={3}
  fileList={pics}
  fileChange={(e) => {
    console.log('e', e)
    setPics(e)
  }}
/>

图片上传封装
UploadPic.tsx

import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { previewImage } from './previewImage';
import isFunction from 'lodash/isFunction';
import AtImagePicker from 'taro-ui/lib/components/image-picker';

const BaseUrl: string = '10.220.xxxx/api/';

export const UploadPic: React.FC<any> = ({
  maxNumber = 3, // 最大数量
  fileList = [], // 默认显示图片
  previewAble = true,
  fileChange,
}) => {


  const _accessoryFileList: any[] = [...fileList] // 后端用图片格式 arr

  const onChange = (files, doType, index) => {
    if (doType === 'add') {
      // add file
      const waitingUploadFiles = files.filter(f => !(f.url.includes('oss/')))
      uploadFile({ path: waitingUploadFiles });
    } else {
      // remove file
      _accessoryFileList.splice(index, 1)
      _fileChange(_accessoryFileList);
    }
  };

  const uploadFile = (data) => {
    let i = data.i ? data.i : 0 // 当前所上传的图片位置
    let success = data.success ? data.success : 0//上传成功的个数
    let fail = data.fail ? data.fail : 0;//上传失败的个数
    Taro.showLoading({
      title: `正在上传第${i + 1}张`
    })
    //发起上传
    Taro.uploadFile({
      url: `${BaseUrl}/upload`,
      header: {
        'content-type': 'multipart/form-data',
        // 'token': data.token // 上传需要单独处理token
      },
      name: 'file',
      filePath: data.path[i].url,
      success: (res) => {
        //图片上传成功,图片上传成功的变量+1
        const responseData = JSON.parse(res.data);
        // console.log('responseData', responseData)
        if (responseData && responseData?.code === 200 && responseData?.data) {
          success++;

          let imgAcc: any = null;
          if (responseData?.data?.downloadUrl) {
            const { downloadUrl } = responseData?.data
            imgAcc = {
              url: downloadUrl
            }
          }

          imgAcc && _accessoryFileList.push(imgAcc)
        } else {
          fail++;

          Taro.showToast({
            title: '上传失败,请稍后重试',
            icon: 'none',
          });
        }
      },
      fail: () => {
        fail++;//图片上传失败,图片上传失败的变量+1
      },
      complete: () => {
        Taro.hideLoading()
        i++;//这个图片执行完上传后,开始上传下一张
        if (i == data.path.length) {   //当图片传完时,停止调用
          Taro.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 2000
          })

          console.log('成功:' + success + " 失败:" + fail);
          _fileChange(_accessoryFileList);
          console.log('----------------_accessoryFileList', _accessoryFileList)
        } else {//若图片还没有传完,则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          uploadFile(data);
        }
      }
    })
  }

  const _fileChange = (_accessoryFileList) => {
    isFunction(fileChange) && fileChange(_accessoryFileList);
  };

  return (
    <View>
      <AtImagePicker
        multiple
        length={3}
        count={9}
        files={fileList}
        onImageClick={(i) => previewAble && previewImage(i, fileList)}
        onChange={onChange}
        showAddBtn={fileList.length < maxNumber}
      />
    </View>
  );
}

图片预览代码:
previewImage.ts

export function previewImage(i, fileList) {

  const urls = fileList.map(item => item.url);

  wx.previewImage({
    current: urls[i], // 当前显示图片的http链接
    urls, // 需要预览的图片http链接列表
  })
}

附:

微信官方api

THE END
posted @   ZerlinM  阅读(326)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示