File Upload
Point 1:
- Example of a FormData() object.
Point 2:
- Append the file obtained during upload to the formdata object.
Point 3:
- Configure the request header of the upload interface.
Method 1: Form submission file (native)
<el-button @click="getFile" style="margin-top: 10px">
<i class="el-icon-upload"></i> {
{$i18n.t('CLICK_UPLOAD')}}
</el-button>
<input
type="file"
ref="file"
style="display: none;"
v-on:change="handleFileUpload($event)"
/>
Get file file
let formData = new FormData();
let file = this.$refs.file.files[0];
formData.append(file, file);
// 调用接口
postUpload(formData).then(() => {
});
Upload interface configuration request header
// 文件上传
export function postUpload(file) {
return axios({
url: "upload",
method: "post",
data: file,
headers: {
"Content-Type": "multipart/form-data",
},
});
}
Method 2: Elementui encapsulated component submission file (vue)
Note: The upload interface needs to configure request headers
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
:http-request="onUpload"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
// 上传文件
onUpload (file) {
let formData = new FormData()
formData.append('file',file.file)
postUpload(formData).then((res) => {
console.log(res)
this.$message.success(this.$t('UPLOAD_SUCCESS'))
}).catch((e) => {
this.$message.error(e.message)
})
},