Example of Vue uploading files using the formData format type
- 2021-11-13 06:41:45
- OfStack
In vue, we generally separate the front and back ends, that is, we need to use axios and other tools to send requests to the background to realize the operation of data.
Among them, file uploading is a difficult one. This article teaches you to upload files in 5 minutes.
1. If the picture is uploaded and the back end needs the front end to transmit formData type data,
<el-button type="primary" @click="uploadFile2()"> Click Upload </el-button>
<input type="file" @change="fileValueChange2()" ref="uploadFile2" enctype="multipart/form-data" style="display:none;" accept="image/jpeg,image/png,image/gif">
We use the native input method to achieve.
uploadFile2(){
// When clicked button This event is triggered when the
// The function is to open the file upload bullet box
this.$refs.uploadFile2.click()
},
fileValueChange2(){
// Triggers when the file is selected input Adj. change Event, this function is entered
var formData = new FormData()
// this.$refs.uploadFile2 Yes vue Get from dom Method of element
// Pass files You can get all the uploaded files, and if it is a loop of multiple files, you can
formData.append( 'file',this.$refs.uploadFile2.files[0])
// You must set the request type
formData.append( 'type', "head");
// If you need to pass id In the case of, refer to the following code
formData.append( 'id', this.id);
// After the configuration is complete, you only need to pass in to the background formData Variable will do
insertNavigationUpload(formData).then(res=>{
console.log ( ' Is it simple? Old iron ' )
})
},
I almost forgot step 1. I won't say much about axios request encapsulation twice. I only show the interface here
export const tMessageNotification = data =>{
return request({
url:'/tMessageNotification/upload',
method: 'POST',
data,
headers: {'Content-Type': 'application/json'},
})
}