前端页面经常需要进行文件上传,那么就需要实现配合后端实现文件上传oss阿里云,下面区分了使用组件和不使用组件进行上传的情况
ant design的文件上传组件如下
<div v-show="addFile">
<a-upload-dragger
:customRequest="uploadFile"
name="file"
:multiple="true"
@change="fileChange"
accept=".pdf,.doc,.docx"
>
<p class="ant-upload-drag-icon">
<a-icon type="inbox" />
</p>
<p class="ant-upload-text">
点击选择上传pdf文件
</p>
<p class="ant-upload-hint">
支持单个或批量上传
</p>
</a-upload-dragger>
</div>
注意需要通过customRequest自定义上传方法
这里我定义了文件需要为pdf和word,如果你有别的需求可以更改accept属性
接下来是具体上传阿里云的代码
注意
- getOss(file)方法是通过后端获取AccessKeyId等数据,当然也可以自己去官方获取
- 如果你没有使用组件库,那么使用下面的方法就可以,如果使用了ant design需要看第三步
ossLoad(file, ossData) {
let fileName = file.name
let fd = new FormData(),
key = ossData.dir + uuid()
fd.append('key', key)
fd.append('success_action_status', '200')
fd.append('x-oss-meta-fullname', fileName)
fd.append('OSSAccessKeyId', ossData.accessKeyId)
fd.append('policy', ossData.policy)
fd.append('signature', ossData.signature)
fd.append('file', file)
// 数据组装完成后,发送上传请求到阿里云oss
axios({
url: ossData.host,
method: 'POST',
data: fd,
processData: false,
cache: false,
contentType: false,
})
.then(res => {
// 拿到结果后,做其他操作
console.log(res);
if (res.status == '200') {
//如果没有使用ant design不写这一行
this.$set(file,'status','done')
}
})
},
async getOss(file) {
// 获取oss信息
let res = await OssSend()
if (res.code == 200) {
this.ossLoad(file, res.data)
}
},
改变文件状态完成上传
- uploadFile方法为上面定义的自定义上传操作,我写成空是因为我只是用它取消了默认发送的请求
- 具体的上传方法我写在了fileChange方法中,以便判断状态
- 这里我手动判断了状态,在状态为’uploading’时调用了getOss进行上传,并且在ossLoad方法中将上传成功后的状态改变了
uploadFile() {},
fileChange(info) {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
} else {
this.getOss(info.file)
}
if (status === 'done') {
this.$message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
this.$message.error(`${info.file.name} file upload failed.`);
}
},
需要注意的地方
- 注意状态判断,如果请求完成不改变状态页面会一直显示文件上传状态
- 如果你没有使用customRequest覆盖默认行为,那么会自动发送请求,所以如果你不使用默认的请求最好把它覆盖掉