SoFunction
Updated on 2025-04-06

Example of Vue uploading files using formData format type

In vue, we generally separate projects from front-end, that is, we need to use tools such as axios to send requests to the background to implement data operations.
Among them, uploading files is a relatively difficult one. This article teaches you how to upload files in five minutes.

1. If the image is uploaded, the backend needs to pass formData type data on the frontend

<el-button type="primary"  @click="uploadFile2()">Click to 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 native input to achieve this.

uploadFile2(){
	// This event will be triggered when the button button is clicked	// The function is to open the file upload pop-up box     this.$refs.()
   },
   fileValueChange2(){
   // After selecting the file, the input change event will be triggered, which will enter this function     var formData = new FormData()
     // this.$refs.uploadFile2 is the method to get the dom element in vue     // You can get all uploaded files through files. If it is multiple file loops, it can     ( 'file',this.$refs.[0])
     // The request type must be set     ( 'type', "head");
     // If you need to pass id, refer to the following code     ( 'id', );
     // After the configuration is completed, you only need to pass the formData variable to the background     insertNavigationUpload(formData).then(res=>{
       ('Is it simple?  Old Tie')
     })
   },

I almost forgot one step, I won't say much about axios requesting secondary encapsulation, I will only show the interface here

export const tMessageNotification = data =>{
  return request({
    url:'/tMessageNotification/upload',
    method: 'POST',
    data,
    headers: {'Content-Type': 'application/json'},
  })
}

This is the article about Vue uploading files using formData format. For more related Vue uploading files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!