Vue implements file upload and download

Vue implements file upload and download

This article example shares the specific code of Vue to upload and download files for your reference. The specific content is as follows

File upload

File upload in Vue is mainly divided into two steps: getting the file in the front end and submitting it to the back end

Get File

The front-end obtains files mainly by using the input box

<el-dialog :title="addName" :visible.sync="dialogAddFile" width="500px" style="padding:0;" @close="resetAdd">
               Attachment name: <el-input v-model="addFileName" autocomplete="off" size="small" style="width: 300px;" ></el-input>
                <div class="add-file-right" style="height:70px;margin-left:100px;margin-top:15px;">
                    <div class="add-file-right-img" style="margin-left:70px;">Upload file:</div>
                    <input type="file" ref="clearFile" @change="getFile($event)" multiple="multiplt" class="add-file-right-input" style="margin-left:70px;" accept=".docx,.doc,.pdf">
                    <span class="add-file-right-more">Supported extensions: .doc .docx .pdf </span>
                </div>
                <div class="add-file-list">
                    <ul>
                        <li v-for="(item, index) in addArr" :key="index"><a >{{item.name}}</a></li>
                    </ul>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitAddFile" size="small">Start uploading</el-button>
                    <el-button @click="resetAdd" size="small">Delete all</el-button>
               </div>
</el-dialog>

The most important thing is this line of code:

File upload is implemented through the file type input box; then multiple files are uploaded by setting multiple="multiplt", and the upload file type restriction is implemented using accept; finally, by listening to the change event, the front end obtains the uploaded file.

getFile(event){
           var file = event.target.files;
           for(var i = 0;i<file.length;i++){
            // Upload type judgment var imgName = file[i].name;
                var idx = imgName.lastIndexOf(".");  
                if (idx != -1){
                    var ext = imgName.substr(idx+1).toUpperCase();   
                    ext = ext.toLowerCase(); 
                     if (ext!='pdf' && ext!='doc' && ext!='docx'){
                       
                    }else{
                          this.addArr.push(file[i]);
                    }   
                }else{
 
                }
           }
       },

The uploaded files can be obtained through event.target.files in the change event, and the type of files obtained is restricted again above.

Data Submission

After obtaining the file data, you need to submit the data to the background, here you can use FormData to submit.

submitAddFile(){
           if(0 == this.addArr.length){
             this.$message({
               type: 'info',
               message: 'Please select the file to upload'
             });
             return;
           }
 
            var formData = new FormData();
            formData.append('num', this.addType);
            formData.append('linkId',this.addId);
            formData.append('rfilename',this.addFileName);
            for(var i=0;i<this.addArr.length;i++){
                formData.append('fileUpload',this.addArr[i]);
            }
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': this.token
            }
          };
          this.axios.post(apidate.uploadEnclosure,formData,config)
            .then((response) => {
                if(response.data.info=="success"){this.$message({
                        type: 'success',
                        message: 'Attachment uploaded successfully!'
                    });
                }
            })
        }

When submitting data, there are two points to note: formData object and Content-Type. After handling these two points, it is the same as other interfaces.

Download the file

The first step is to get a list of files from the server and display them:

<div class="about-file">
    <div class="about-file-title">Related Materials</div>
    <ul>
        <li v-for="(item, index) in tenEnclosure.rows" :key="index">
              <a target="_self" >{{item.tenPencSourname}}</a>
              <span @click="toxiazai(index,4,item.tenureId)" title="Download"></span>
              <span @click="toshanchu(index,4,item.tenureId)" title="Delete"></span>
       </li>
   </ul>
</div>

Then complete the click download event:

toxiazai(index,num,id){
          var tempForm = document.createElement("form"); //Create a form, and follow the various parameters of the form tempForm.id = "tempForm1";
          tempForm.method = "post";
          tempForm.action = apidate.downloadEnclosure;
          tempForm.target="_";
          var hideInput1 = document.createElement("input");
          hideInput1.setAttribute('type','hidden');
          hideInput1.setAttribute('name','linkId');
          hideInput1.setAttribute('id','linkId');
          hideInput1.setAttribute('value',id);
          tempForm.appendChild(hideInput1);
 
          var hideInput2 = document.createElement("input");
          hideInput2.setAttribute('type','hidden');
          hideInput2.setAttribute('name','num');
          hideInput2.setAttribute('id','num');
          hideInput2.setAttribute('value',num);
          tempForm.appendChild(hideInput2);
 
 
          if(document.all){
            tempForm.attachEvent("onsubmit",function(){}); //IE
          }else{
            var subObj = tempForm.addEventListener("submit",function(){},false); //firefox
          }
          document.body.appendChild(tempForm);
          if(document.all){
            tempForm.fireEvent("onsubmit");
          }else{
            tempForm.dispatchEvent(new Event("submit"));
          }
          tempForm.submit();//Submit POST requestdocument.body.removeChild(tempForm);
},

Open the file online

On the PC side, many files are downloaded, but on the mobile phone side, most of them are opened directly online. If you want to open the file online, you can use the href attribute of the a tag to achieve

<ul>
     <li v-for="(item,index) in noticeList" v-bind:key="index" class="person-list" @click="notice(index)">
          <div class="person-list-name">
              <a v-bind:href="[filePrefix+item.uuid_name]" rel="external nofollow" rel="external nofollow" >{{item.file_name}}</a>
         </div>
         <div class="person-list-time">Upload time: {{item.create_time}}</div>
     </li>
</ul>

Because when using this method to open a file, a complete path name is required, but when getting the list from the background, it is usually a relative path, so path splicing is required: v-bind:href="[filePrefix+item.uuid_name]"

Image upload and preview

After uploading the file, you can get the file name for display. However, if you upload pictures in this way, the display will no longer be the picture name, but the picture display.

For example, to achieve the above effect, use input to upload the image

<div class="list-img">
                <ul>
                    <li v-for="(item,index) in imgArr" :key="index">
                        <img :src="item.path" alt="" >
                        <a @click="todel(index)"></a>
                    </li>
           <li>
            <div class="addImg" v-if="imgArr.length<3">
                  <span class="add">Upload picture</span>
                  <span class="add">(Upload up to 3 photos)</span>
                  <input type="file" @change="getFile($event)" accept=".jpg,.png,.bmp,.gif">
             </div>
         </li>
     </ul>
</div>
getFile(event){
            var file = event.target.files;
            for(var i = 0;i<file.length;i++){
               // Upload type judgment var imgName = file[i].name;
                var idx = imgName.lastIndexOf(".");  
                if (idx != -1){
                    var ext = imgName.substr(idx+1).toUpperCase();   
                    ext = ext.toLowerCase(); 
                    if (ext!='jpg' && ext!='png' && ext!='bmp' && ext!='gif'){
                        
                    }else{
                            this.imgArr.push(file[i]);
                    }   
                }else{
 
                }
            }
        },

Because when printing the event object, I found that the uploaded picture contained a path field, which corresponds to the address of the picture on the device. I took it for granted that I could display the picture in this way. As a result, I obviously got an error. I checked it on the Internet and found that to display the pictures uploaded using input, I need to use FileReader.

Specifically, the picture obtained by input cannot be displayed immediately. The two are completely different things, so an array is needed to store the displayed pictures.

getFile(event){
            var file = event.target.files;
            let that = this;
            for(var i = 0;i<file.length;i++){
               // Upload type judgment var imgName = file[i].name;
                var idx = imgName.lastIndexOf(".");  
                if (idx != -1){
                    var ext = imgName.substr(idx+1).toUpperCase();   
                    ext = ext.toLowerCase(); 
                    if (ext!='jpg' && ext!='png' && ext!='bmp' && ext!='gif'){
                        
                    }else{
                            that.imgArr.push(file[i]);
                    }   
                }else{
 
                }
                //Show uploaded pictures let reader = new FileReader()
                reader.readAsDataURL(file[i])
                reader.onload = function(e) {
                    that.imgShow.push(this.result);
                }
            }
        },

In this way, when submitting data, imgArr is used, and when displaying, imgShow is used

Another thing to note is that there is also a delete operation. The delete operation here is not only invisible on the interface, but also means that the deleted photos do not need to be passed to the background. Therefore, both arrays need to be deleted.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Springboot+vue to realize file upload and download
  • Vue excel upload preview and table content download to excel file
  • Springboot integrates vue to upload and download files
  • Vue implements file upload, reading and download functions
  • Two ways to implement Excel file upload and download functions in Vue
  • vue-cli+axios realizes file upload and download function (download receiving background returns file stream)
  • Vue implements file upload and download functions

<<:  Detailed tutorial on installing Python 3 virtual environment in Ubuntu 20.04

>>:  SQL injection vulnerability process example and solution

Recommend

Nginx anti-crawler strategy to prevent UA from crawling websites

Added anti-crawler policy file: vim /usr/www/serv...

Explanation of the working mechanism of namenode and secondarynamenode in Hadoop

1) Process 2) FSImage and Edits Nodenode is the b...

How to connect to MySQL visualization tool Navicat

After installing Navicat The following error may ...

Why MySQL does not recommend using subqueries and joins

To do a paginated query: 1. For MySQL, it is not ...

MySQL restores data through binlog

Table of contents mysql log files binlog Binlog l...

Tutorial on how to modify element.style inline styles

Preface When we were writing the web page style a...

MySQL data aggregation and grouping

We often need to summarize data without actually ...

5 Easy Ways to Free Up Space on Ubuntu

Preface Most people will probably perform this op...

Measured image HTTP request

Please open the test page in a mainstream browser...

Linux uses dual network card bond and screwdriver interface

What is bond NIC bond is a technology that is com...

Detailed explanation of samba folder sharing server configuration under centos

1. Introduction Recently I found that there are m...

How to implement nginx smooth restart

1. Background During the server development proce...

React's context and props explained

Table of contents 1. context 1. Usage scenarios 2...