AntDesign - upload 上传组件 - 自定义函数customRequest可以自定义参数、请求方式、headers 等

在这里插入图片描述


<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
		}
	})
}
// 图片上传失败,展示一个失败的图片提示


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值