原生
<input type="file" ref="fileInput" accept=".doc,.docx"
@change="handleUploadFile"/>
<a-button>
<template #icon><UploadOutlined />
选择文件
</a-button>
const fileInput=ref<HTMLElement>()
const handleUploadFile=()=>{
const files=fileInput.value?.files
}
组件:选择文件,通过某个按钮进行上传操作
<a-upload
v-model:file-list="fileList"
@preview="handlePreview"
:data="uploadData"
:before-upload="beforeUpload"
@remove='handleRemove'
name='fileList'
>
<a-button>
<upload-outlined></upload-outlined>
选择文件 </a-button>
</a-upload>
<a-button @click='handleUpload'>
<template #icon><UploadOutlined />
上传文件
</a-button>
const formDataTranfer =(params:object)=>{
const formData=new FormData()
Object.keys(params).forEach(key=>{
Object.prototype.toString.call((params as any)[key])==='[object File]'
|| Object.prototype.toString.call((params as any)[key])==='[object String]'){
formData.append(key,(params as any)[key]))
}else{
formData.append(key,JSON.stringify((params as any)[key])))
}
})
return formData
}
const fileList= ref<UploadProps['fileList']>([])
const beforeUpload: UploadProps['beforeUpload'] = file => {
fileList.value=[...fileList.value,file]
return false
};
const handleUpload=()=>{
const formData=new FormData()
fileList.value?.forEach((file:any)=>{
formData.append('file',file as any)
})
formData.append('other','value ')
const res=upload(formData)
}
const handleRemove: UploadProps['onRemove'] = file => {
const index = fileList.value.indexOf(file);
const newFileList = fileList.value.slice();
newFileList.splice(<number>index, 1);
fileList.value = newFileList;
};