vue 選擇圖片(限定大小)上傳到服務器


FormData:

 https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects 
成果:

 

html:

         <div class="pdt15 pdb15">
                    <div id="preview" class="preview" v-for="(Img, index) in files" :key="index">
                        <img src="./img/cross.png" alt="叉" class="delimg" @click="delimg(index)">
                        <img :src="Img.path" alt="" class="addimg">
                    </div>
                    <label for="browse" class="browse">
                        <input class="hidden" id="browse" type="file" accept="image/*" @change="previewFiles($event)" multiple>
                        <img src="./img/icon-photo.png" width="100" height="100" alt="照相機">
                    </label>
                </div>

js:

 1 //上傳圖片
 2         previewFiles(e){
 3             let files = e.target.files
 4             for (let i = 0; i < files.length; i++) {
 5                 if (files[i].size/1024/1024 > 2) { //限制每張上傳圖片的大小
 6                     alert('第'+(i+1)+'張圖片大於2M,請上傳小於2M的圖片');
 7                     return; 
 8                 }
 9             }
10             // console.log(files[0].size/1024/1024);
11             let formData = new FormData();
12             formData.append("action","upresumefile");//調用它的append()方法來添加字段
13             for (let i = 0; i < files.length; i++) {
14                 formData.append("file[]",files[i]);
15             }
16 17             this.$http.post('/API/app/infointerface.ashx',formData)
18             .then((res) => {
19                 if (res.data.Result) {
20                     this.files = this.files.concat(res.data.Data); //把服務器返回的圖片路徑獲取下來,在頁面顯示
21                     // console.log(this.files);
22                 }
23             })
24         },
25         //刪除圖片
26         delimg(ind){
27             this.files.splice(ind, 1);   
28         },

 FormData對象用以將數據編譯成鍵值對,以便用XMLHttpRequest來發送數據。其主要用於發送表單數據,但亦可用於發送帶鍵數據(keyed data)

對於formData對象的簡單常見用法推薦看:https://blog.csdn.net/zqian1994/article/details/79635413

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM