SoFunction
Updated on 2025-04-05

Vue+FormData+axios realizes image upload function

When using Vue + FormData + axios to implement image upload function, you can follow the following steps:

Sample code

1. First, in the Vue component, create a data attribute to store the selected file and upload status:

data() {
  return {
    file: null,
    uploading: false
  };
}

2. In the template, create a file selection input and an upload button:

<input type="file" @change="onFileChange">
<button @click="uploadFile">Upload</button>

3. Create a method to handle file selection events and store the selected file in the data attribute:

methods: {
  onFileChange(event) {
     = [0];
  },
  uploadFile() {
    if (!) {
      return;
    }
     = true;
    let formData = new FormData();
    ('file', );
    ('/upload', formData)
      .then(response =&gt; {
        // Process the logic of successful upload         = false;
      })
      .catch(error =&gt; {
        // Process the logic of upload failure         = false;
      });
  }
}

4. On the server side, use or other backend technologies to process file upload requests. In this example, we use the Express framework to handle upload requests:

const express = require('express');
const multer = require('multer');
const app = express();
const storage = ({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, );
  }
});
const upload = multer({ storage: storage });
('/upload', ('file'), (req, res) =&gt; {
  // Process file upload logic  ('File uploaded');
});
(3000, () =&gt; {
  ('Server started on port 3000');
});

In this way, you can use Vue + FormData + axios to implement the image upload function. When the user selects a file and clicks the upload button, the file will be sent to the server for processing. On the server side, you can save files and execute other logic as needed. The status during the upload process can be processed in the Vue component to perform corresponding operations when the upload is successful or failed.

All codes in the whole

Here is a more detailed code implementation example:

In the front end, use Vue + FormData + axios to achieve image upload function:

&lt;template&gt;
  &lt;div&gt;
    &lt;input type="file" @change="onFileChange"&gt;
    &lt;button @click="uploadFile"&gt;Upload&lt;/button&gt;
    &lt;div v-if="uploading"&gt;Uploading...&lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import axios from 'axios';
export default {
  data() {
    return {
      file: null,
      uploading: false
    };
  },
  methods: {
    onFileChange(event) {
       = [0];
    },
    uploadFile() {
      if (!) {
        return;
      }
       = true;
      let formData = new FormData();
      ('file', );
      ('/upload', formData)
        .then(response =&gt; {
          // Process the logic of successful upload           = false;
        })
        .catch(error =&gt; {
          // Process the logic of upload failure           = false;
        });
    }
  }
};
&lt;/script&gt;

In the backend, use and Express to process file upload requests:

const express = require('express');
const multer = require('multer');
const app = express();
const storage = ({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, );
  }
});
const upload = multer({ storage: storage });
('/upload', ('file'), (req, res) =&gt; {
  // Process file upload logic  ('File uploaded');
});
(3000, () =&gt; {
  ('Server started on port 3000');
});

In this example, when the user selects a file and clicks the upload button, the file will be sent to the server for processing. On the server side, use the mult middleware to handle file upload requests. In the configuration of the mult, specify the storage destination folder and file name of the file. Create a route to handle file upload requests and use the () method to handle single file uploads. In the routing processing function, uploaded files can be processed as needed, such as saving files to a specified location on the server. The status during the upload process can be processed in the Vue component to perform corresponding operations when the upload is successful or failed.

Use scenarios

Here are detailed instructions on the advantages and disadvantages of Vue + FormData + axios image upload and usage scenarios:

advantage:

  • Simple and easy to use: Using Vue + FormData + axios to achieve image uploading function is relatively simple, and does not require complex configuration and dependencies.
  • Real-time feedback: During the upload process, you can provide real-time feedback on the upload progress and status to provide a better user experience.
  • Cross-platform compatibility: Vue + FormData + axios can be used in various front-end frameworks and browsers, with good cross-platform compatibility.
  • Scalability: Functional expansion and customization can be performed according to actual needs, such as adding image previews, limiting uploaded file types, etc.

shortcoming:

  • Dependence on the network: The image upload function depends on network connection. If the network is unstable or slow, it may cause a longer upload time or failure of upload.
  • File size limit: The browser has a limit on file upload size, which is usually 2MB by default, and needs to be configured and processed for large file uploads according to requirements.
  • Security: Pay attention to the security of file upload to prevent malicious file uploads and attacks.

Use scenarios:

  • Image upload: Vue + FormData + axios is suitable for the development of image upload function, which can easily realize the function of users selecting images and uploading them to the server.
  • File upload: In addition to image upload, Vue + FormData + axios is also suitable for uploading other types of files, such as documents, videos, etc.
  • Multi-file upload: If you need to upload multiple files at the same time, you can support multiple file upload by modifying the code.
  • Image preview: You can combine Vue's image preview plug-in to enable users to preview the picture on the front end and then upload it.
  • Upload progress display: If you need to display the upload progress, you can obtain the upload progress through axios' onUploadProgress event and display it on the front end.

In summary, Vue + FormData + axios is suitable for simple image upload and file upload scenarios, which can quickly implement upload functions and provide a good user experience. If more complex file upload functions are required, it may be necessary to combine other technologies and tools to achieve this.

The above is the detailed content of Vue+FormData+axios implementing the image upload function. For more information about Vue FormData axios image upload, please follow my other related articles!