uni上传图片

412 阅读1分钟

前言

记录一下,方便自己后续使用~
项目中使用了uview-plus组件。

界面

2c84f5399a46717fa01332baabd54e0.jpg

封装上传组件

<template>
  <up-upload
    :file-list="fileList"
    name="1"
    :max-count="1"
    @after-read="uploadFile"
    @delete="deletePic"
  />
</template>

<script setup>
import { getOssToken } from '@/api/index'

const props = defineProps({
  src: {
    type: String,
    default: ''
  }
})

// 组件中file-list需要的格式: [{url: 'xxx',otherProp: ''}]
// 因为后端传递的都是字符串,所以统一在组件中处理成满足条件的格式
const initFile = () => {
  const list = Array.isArray(props.src) ? props.src : props.src ? [props.src] : []
  fileList.value = list.map(v => ({ url: v }))
}
const fileList = ref([])
watch(() => [props.src], () => {
  initFile()
})
onLoad(() => {
  initFile()
})

// 后端使用云存储, 所以需要先获取一些必要的token等
const getUploadToken = async () => {
  const tokenList = {}
  await getOssToken().then(({ data }) => {
    tokenList.url = data.host
    tokenList.key = data.key
    tokenList.policy = data.policy
    tokenList.OSSAccessKeyId = data.OSSAccessKeyId
    tokenList.signature = data.signature
  })
  return tokenList
}

const emit = defineEmits(['uploadSuccess'])
// 上传文件
const uploadFile = async (event) => {
  const tokenList = await getUploadToken()
  uni.uploadFile({
    url: tokenList.url,
    filePath: event.file.url,
    name: 'file',
    formData: {
      key: tokenList.key, // 文件名
      policy: tokenList.policy, // 后台获取超时时间
      OSSAccessKeyId: tokenList.OSSAccessKeyId, // 后台获取临时ID
      success_action_status: '200', // 让服务端返回200,不然,默认会返回204
      signature: tokenList.signature // 后台获取签名
    },
    success: function ({ statusCode }) {
      if (statusCode === 200) {
        fileList.value.push({ url: tokenList.url + '/' + tokenList.key })
        // 上传成功,把文件传给父级。以供父级后续使用。
        emit('uploadSuccess', fileList.value)
      }
    }
  })
}
// 删除图片
const deletePic = (index) => {
  fileList.value.splice(index, 1)
}
</script>

组件调用

<template>
    <img-upload
      :src="codeParam.url"
      @upload-success="uploadSuccess"
    />
</template>    

<script>

    const imageurl = ref([])
    const uploadSuccess = (list) => {
      imageurl.value = list
    }
</script>