uploadImage.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
import { resetData } from '@/utils' import config from '@/api/config/upload' import { ImageReturn } from '@/api/model/uploadModel' export default function useUploadImage(fileList: Ref<object[]>) { const deletePic = (event: { index: number }) => { fileList.value.splice(event.index, 1) } const afterRead = async (event: { file: ConcatArray<never> }) => { const lists = [].concat(event.file) as { url: string }[] let fileListLen = fileList.value.length lists.map((item: object) => { fileList.value.push({ ...item, status: 'uploading', message: '上传中' }) }) for (let i = 0; i < lists.length; i++) { const result = (await uploadFilePromise(lists[i].url)) as { url: string; uri: string } const item = fileList.value[fileListLen] fileList.value.splice(fileListLen, 1, { ...item, status: 'success', message: '', url: result.uri, uri: result.url }) fileListLen++ } } const uploadFilePromise = (url: string) => { return new Promise<ImageReturn['data']>(resolve => { uni.uploadFile({ url: config.image, // 仅为示例,非真实的接口地址 filePath: url, header: { token: uni.getStorageSync('token') }, name: 'file', formData: resetData({}), success: res => { setTimeout(() => { const data = JSON.parse(res.data) resolve(data.data) }, 1000) } }) }) } return { deletePic, afterRead, uploadFilePromise } } |
页面使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<template> <view> <view class="upload-box"> <u-upload name="file1" multiple :file-list="fileList1" :max-count="1" @after-read="file1.afterRead" @delete="file1.deletePic" /> </view> </view> </template> <script setup lang="ts"> import useUploadImage from '@/composition/uploadImage' const fileList1 = ref<{ uri: string; url: string }[]>([]) const file1 = useUploadImage(fileList1) </script> <style lang="scss"> </style> |