ant-design-vue组件自带的upload通过action上传到服务器上,通常项目中都是自定义上传的,通过customRequest这个勾子覆盖掉我们的action上传。
<template>
<div class="clearfix">
<a-upload :fileList="fileList" :remove="handleRemove" :customRequest =customRequest :beforeUpload="beforeUpload">
<a-button> <a-icon type="upload" /> Select File </a-button>
</a-upload>
<a-button
type="primary"
@click="handleUpload"
:disabled="fileList.length === 0"
:loading="uploading"
style="margin-top: 16px"
>
{{ uploading ? 'Uploading' : 'Start Upload' }}
</a-button>
</div>
</template>
<script>
import reqwest from 'reqwest';
export default {
data() {
return {
fileList: [],
uploading: false,
};
},
methods: {
handleRemove(file) {
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
},
beforeUpload(file) {
this.fileList = [...this.fileList, file];
return false;
},
customRequest (data) {
const formData = new FormData()
formData.append('file', data.file)
formData.append('token', 'aiufpaidfupipiu')//随便写一个token示例
this.saveFile(formData)
},
saveFile (formData) {
this.form.validateFields((err, values) => {
if (!err) {
let that = this
this.axios(
{
method: 'post',
url: 'http://localhost:4785/api/values/PostSingle',
data: formData
})
.then((response) => {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
})
},
handleUpload() {
const { fileList } = this;
const formData = new FormData();
fileList.forEach(file => {
formData.append('files[]', file);//后面再加上token
});
this.uploading = true;
// You can use any AJAX library you like
request({
url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
method: 'post',
processData: false,
data: formData,
success: () => {
this.fileList = [];
this.uploading = false;
this.$message.success('upload successfully.');
},
error: () => {
this.uploading = false;
this.$message.error('upload failed.');
},
});
},
},
};
</script>