How to write code for vue batch upload

WBOY
Release: 2023-05-08 09:38:06
Original
1147 people have browsed it

In recent years, front-end frameworks have become the tool of choice for many front-end developers, among which vue.js is favored by developers for its easy learning curve and easy maintenance. In vue.js, implementing the file upload function is one of the very common requirements, and batch upload is used by various websites. So how to implement batch upload in vue.js? The following will introduce in detail how vue.js implements batch upload.

1. Simple file upload

Before introducing batch upload, let’s first take a look at the simple single file upload implementation in vue.js. Assume that the file we want to upload is as follows:

<input type="file" @change="handleFileUpload"/>
Copy after login

Add the handleFileUpload function in the methods of vue.js to handle file upload:

handleFileUpload() {
  const file = event.target.files[0]; //获取文件对象
  const formData = new FormData(); //建立FormData对象
  formData.append('file', file); //将文件添加到FormData中
  axios.post('/file/upload', formData)//使用axios发送post请求上传文件
       .then(response => {
        console.log(response);//上传成功后的响应结果
       })
}
Copy after login

In this code, we use the axios library to Send a post request to upload the file, but this can also be achieved using any other library or native ajax. Of course, in actual projects, we may need to use Authentication Token or CSRF Token to ensure security.

2. Multiple file upload

After understanding single file upload, let’s introduce the method of vue.js to implement multi-file upload. Add the input of multi-select files in html:

<input type="file" ref="fileInput" @change="handleMultipleFileUpload" multiple>
Copy after login

Then add the handleMultipleFileUpload function in methods:

handleMultipleFileUpload() {
  const files = this.$refs.fileInput.files;//获取上传的文件对象
  const formData = new FormData();//建立FormData对象
  for(let i=0 ;i<files.length ;i++){
    formData.append('files', files[i]);//将文件添加到FormData对象中
  }
  axios.post('/file/multiple_upload', formData)//发送post请求上传多个文件
       .then(response => {
         console.log(response);//上传成功后的响应结果
       })
}
Copy after login

Through this code, we can upload multiple files. Different from a single file, we need to Add files to the formData object in sequence. I believe you can already understand how to simply upload multiple files in vue.js.

3. Implement multi-file upload with progress bar

However, the above multi-file upload function needs to be further expanded. For example, if we want to display the upload progress bar, instead of knowing the upload status only after the upload is successful, we need to use the XMLHttpRequest object to implement the upload progress bar. The code is as follows:

handleMultipleFileUpload() {
    const files = this.$refs.fileInput.files;//获取上传的文件对象
    const formData = new FormData(); //建立FormData对象
    for(let i=0 ;i<files.length ;i++){
      formData.append('files', files[i]); //将文件添加到FormData对象中
    }
    const xhr = new XMLHttpRequest();//创建XMLHttpRequest对象实现进度条
    //upload.addEventListener用于上传进度监听
    xhr.upload.addEventListener("progress", function(evt){
      if(evt.lengthComputable){
        const percentComplete = Math.round(evt.loaded * 100 / evt.total);//计算上传进度
        console.log(`上传进度:${percentComplete}%`);
      }
    }, false);
    //ajax完成后触发的事件
    xhr.onreadystatechange=function(evt){
      if(xhr.readyState===4){//上传完成
        console.log(xhr.responseText);//上传完成后的响应结果
      }
    }
    //发送post请求上传文件
    xhr.open("POST", "/file/multiple_upload");
    xhr.send(formData);
  }
Copy after login

In fact, when we upload special files such as streaming media and large amounts of files, the above upload method may be limited. Therefore, it is very necessary to understand the types of uploaded files, file size restrictions, network speed, user needs, etc., and choose the corresponding upload method.

To sum up, this article introduces the method of vue.js to realize single file upload and multi-file upload, and realizes the effect of upload progress bar through XMLHttpRequest object. I believe these methods can help you better complete the file upload function. At the same time, in actual projects, it is also necessary to consider how the back-end server handles uploaded files and how to prevent file leaks and data tampering and other related issues.

The above is the detailed content of How to write code for vue batch upload. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!