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

JavaScript clicks the button to generate a 4-digit random verification code

This article example shares the specific code of ...

Pure CSS3 to achieve pet chicken example code

I have read a lot of knowledge and articles about...

Three Ways to Lock and Unlock User Accounts in Linux

If you already have some kind of password policy ...

Pure CSS to modify the browser scrollbar style example

Use CSS to modify the browser scroll bar style ::...

Implementation code of html floating prompt box function

General form prompts always occupy the form space...

Native js drag and drop function to create a slider example code

Drag and drop is a common function in the front e...

js canvas realizes random particle effects

This article example shares the specific code of ...

Usage of if judgment in HTML

In the process of Django web development, when wr...

MySQL Series II Multi-Instance Configuration

Tutorial Series MySQL series: Basic concepts of M...

Example of using JS to determine whether an element is an array

Here are the types of data that can be verified l...

HTML n ways to achieve alternate color code sample code

This article mainly introduces the sample code of...

Today I will share some rare but useful JS techniques

1. Back button Use history.back() to create a bro...