<a-upload
action="http://192.168.110.171:5201/message/wechatReply/uploadToAliOss"
:headers="{
'User-Token': 'b03255fe-b76e-4c1a-b536-2c63e48ced86',
}"
:show-upload-list="{ showRemoveIcon: true }"
:beforeUpload="handleBeforeUpload"
:customRequest="customRequest"
list-type="picture-card"
// 预览
@preview="handlePreview"
// 预览
// 删除
@remove="handleRemove"
// 删除
// 图片上传失败,展示一个error的提示
@change="handleChange"
:file-list="fileList"
// 图片上传失败,展示一个error的提示
>
<upload-outlined></upload-outlined>
上传图片
</a-upload>
const imgList = ref<Array<string>>([])
const handleBeforeUpload = (file: any, fileList: any) => {
console.log('file=', file)
console.log('fileList=', fileList)
return true
}
const customRequest = (option: any) => {
const { onSuccess, onError, file, action, data = {} } = option
// 自定义参数名
const formData = new FormData()
formData.append('file', file)
// 添加其他自定义数据
// Object.keys(data).forEach(key => {
// formData.append(key, data[key])
// })
fetch(action, {
headers: {
'User-Token': 'b03255fe-b76e-4c1a-b536-2c63e48ced86',
},
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(result => {
onSuccess(result, file)
// console.log('result=', result)
if (result && result.data != null) {
imgList.value.push(result.data)
} else {
message.error('图片太大,上传失败了')
}
.catch(error => {
onError(error)
})
}
// 预览
const handlePreview = async (file: any) => {
if (file && file.response) {
imgView.value.showModal([file.response.data])
} else {
message.error('预览失败!')
}
}
// 删除图片
const handleRemove = (file: any) => {
// console.log('删除=', file)
// console.log('删除=', file.response.data)
if(file.status != 'error'){
imgList.value = imgList.value.filter(item => item != file.response.data)
}
}
// 图片上传失败,展示一个失败的图片提示
interface FileItem {
uid: string
name?: string
status?: string
}
const fileList = ref<FileItem[]>([])
interface FileInfo {
file: FileItem
fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
fileList.value = newFileList.map(item => {
if (item.response && item.response.result == false) {
return {
uid: '-5',
name: 'image.png',
status: 'error',
}
} else {
return item
}
})
}
// 图片上传失败,展示一个失败的图片提示
AntDesign - upload 上传组件 - 自定义函数customRequest可以自定义参数、请求方式、headers 等
于 2024-04-25 17:47:46 首次发布