vxe-upload vue 實現附件上傳、手動批量上傳附件的方式
查看官網:https://vxeui.com
安裝
npm install vxe-pc-ui@4.6.47
// ...
import VxeUIAll from 'vxe-pc-ui'
import 'vxe-pc-ui/lib/style.css'
// ...createApp(App).use(VxeUIAll).mount('#app')
// ...
上傳附件支持失敗重新上傳
自定義重新上傳,通過參數 show-error-status 啟用,當上傳失敗時,可以點擊重新上傳按鈕
<template><div><vxe-upload v-model="fileList" multiple :limit-count="6" :limit-size="50" show-progress show-error-status auto-hidden-button :upload-method="uploadMethod"></vxe-upload></div>
</template><script setup>
import { ref } from 'vue'
import axios from 'axios'const fileList = ref([])// 后端接口模擬請求失敗
const uploadMethod = ({ file, updateProgress }) => {const formData = new FormData()formData.append('file', file)return axios.post('/api/pub/upload/single?randomError=1', formData, {onUploadProgress (progressEvent) {const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 0))updateProgress(percentCompleted)}}).then((res) => {return {...res.data}})
}
</script>
上傳附件、手動批量上傳
當需要手動批量提交上傳時,可以通過 aotu-submit=false 關閉自動提交,然后手動調用 submit() 方法提交
<template><div><vxe-button status="primary" @click="submitEvent">點擊手動上傳</vxe-button><vxe-uploadmultipleshow-progressv-model="fileList"ref="refUpload"button-text="選擇文件或拖拽到此":auto-submit="false":limit-count="9":limit-size="50":upload-method="uploadMethod"></vxe-upload></div>
</template><script setup>
import { ref } from 'vue'
import axios from 'axios'const refUpload = ref()
const fileList = ref([])const uploadMethod = ({ file, updateProgress }) => {const formData = new FormData()formData.append('file', file)return axios.post('/api/pub/upload/single', formData, {onUploadProgress (progressEvent) {const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 0))updateProgress(percentCompleted)}}).then((res) => {return {...res.data}})
}const submitEvent = () => {const $upload = refUpload.valueif ($upload) {$upload.submit()}
}
</script>
上傳附件,可以單個點擊上傳、也可以批量上傳
還可以通過 show-submit-button 顯示上傳按鈕,單個提交或者手動提交單個。如果上傳失敗也可以通過 show-error-status 顯示重新上傳按鈕
<template><div><vxe-button status="primary" @click="submitEvent">點擊手動上傳</vxe-button><vxe-uploadmultipleshow-progressshow-submit-buttonshow-error-statusv-model="fileList"ref="refUpload"button-text="選擇文件或拖拽到此":auto-submit="false":limit-count="9":limit-size="50":upload-method="uploadMethod"></vxe-upload></div>
</template><script setup>
import { ref } from 'vue'
import axios from 'axios'const refUpload = ref()
const fileList = ref([])const uploadMethod = ({ file, updateProgress }) => {const formData = new FormData()formData.append('file', file)return axios.post('/api/pub/upload/single?randomError=1', formData, {onUploadProgress (progressEvent) {const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 0))updateProgress(percentCompleted)}}).then((res) => {return {...res.data}})
}const submitEvent = () => {const $upload = refUpload.valueif ($upload) {$upload.submit(true)}
}
</script>
上傳圖片的詳細用法看這里