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

The complete code of the uniapp packaged applet radar chart component

Effect picture: The implementation code is as fol...

Writing methods that should be prohibited in native JS

Table of contents Block-level functions Directly ...

js code that associates the button with the enter key

Copy code The code is as follows: <html> &l...

Basic Implementation of AOP Programming in JavaScript

Introduction to AOP The main function of AOP (Asp...

MySQL's conceptual understanding of various locks

Optimistic Locking Optimistic locking is mostly i...

Summary of some efficient magic operators in JS

JavaScript now releases a new version every year,...

Mysql Sql statement comments

You can add comments to MySQL SQL statements. Her...

Windows Server 2019 Install (Graphical Tutorial)

Windows Server 2019 is the latest server operatin...

SQL Get stored procedure return data process analysis

This article mainly introduces the analysis of th...

Graphic tutorial on installing Mac system in virtual machine under win10

1. Download the virtual machine version 15.5.1 I ...

JavaScript+HTML to implement student information management system

Table of contents 1. Introduction 2. Rendering 3....

Detailed explanation of invisible indexes in MySQL 8.0

Word MySQL 8.0 has been released for four years s...

How to strike a balance between ease of use and security in the login interface

Whether you are a web designer or a UI designer, ...

Specific use of lazy loading and preloading in js

Delayed loading (lazy loading) and preloading are...

Detailed explanation of the solution to Ubuntu dual system stuck when starting

Solution to Ubuntu dual system stuck when startin...