瀏覽器上傳圖片到服務端,我用過兩種方法:
1.本地圖片轉(zhuǎn)換成base64,然后通過普通的post請求發(fā)送到服務端。
操作簡單,適合小圖,以及如果想兼容低版本的ie沒辦法用此方法
2.通過form表單提交。
form表單提交圖片會刷新頁面,也可以時form綁定到一個隱藏的iframe上,可以實現(xiàn)無刷新提交數(shù)據(jù)。但是如果想傳輸多條form表單數(shù)據(jù),需要寫很多dom,同時還要寫iframe,太麻煩。
目前感覺比較干凈的辦法就是通過axios的post請求,發(fā)送form數(shù)據(jù)到后臺。
html部分,至于界面優(yōu)化,可以把input file的opacity設(shè)置為0,點擊其父容器,即觸發(fā)file
代碼如下:
<input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>
axios的post請求,發(fā)送form數(shù)據(jù)部分,這樣就可以無刷新的提交form數(shù)據(jù)到后臺
update(e){ let file = e.target.files[0]; let param = new FormData(); //創(chuàng)建form對象 param.append('file',file,file.name);//通過append向form對象添加數(shù)據(jù) param.append('chunk','0');//添加form表單中其他數(shù)據(jù) console.log(param.get('file')); //FormData私有類對象,訪問不到,可以通過get判斷值是否傳進去 let config = { headers:{'Content-Type':'multipart/form-data'} }; //添加請求頭 this.axios.post('http://upload.qiniu.com/',param,config) .then(response=>{ console.log(response.data); }) }
以下部分是擴展
vue開發(fā)環(huán)境下,上傳圖片到七牛
最近著手的約能人項目,需要上傳圖片到七牛,但是感覺只是簡單的上傳圖片還需要引七牛的js,太麻煩了,就自己一切從簡。實現(xiàn)邏輯:獲取后臺返回的七牛token,然后axios的post請求,發(fā)送form數(shù)據(jù)到七牛。
七牛的token是其平臺封裝好的,直接在自己服務器配置就能獲取到 在其官網(wǎng)上可以找到直接能用的代碼 ,在七牛平臺獲取到后,返回給前臺直接拿就好了
以下是直接上傳圖片到七牛,不需要安裝七牛亂七八糟的js,只需要通過七牛的form表單上傳就行了。
update(e){ let file = e.target.files[0]; let d = new Date(); let type = file.name.split('.'); let tokenParem = { 'putPolicy':'{\"name\":\"$(fname)\",\"size\":\"$(fsize)\",\"w\":\"$(imageInfo.width)\",\"h\":\"$(imageInfo.height)\",\"hash\":\"$(etag)\"}', 'key':'orderReview/'+d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate()+'/'+d.valueOf()+'.'+type[type.length-1], 'bucket':this.domain,//七牛的地址,這個是你自己配置的(變量) }; let param = new FormData(); //創(chuàng)建form對象 param.append('chunk','0');//斷點傳輸 param.append('chunks','1'); param.append('file',file,file.name) console.log(param.get('file')); //FormData私有類對象,訪問不到,可以通過get判斷值是否傳進去 let config = { headers:{'Content-Type':'multipart/form-data'} }; //先從自己的服務端拿到token this.axios.post(api.uploadToken,qs.stringify(tokenParem)) .then(response=>{ this.token = response.data.uploadToken; param.append('token',this.token); if(this.images.length>8){ alert('不能超過9張'); return; } this.uploading(param,config,file.name);//然后將參數(shù)上傳七牛 return; }) }, uploading(param,config,pathName){ this.axios.post('http://upload.qiniu.com/',param,config) .then(response=>{ console.log(response.data); let localArr = this.images.map((val,index,arr)=>{ return arr[index].localSrc; }) if(!~localArr.indexOf(pathName)){ this.images.push({'src':this.showUrl+response.data.key,'localSrc':pathName}); }else{ alert('已上傳該圖片'); } }) },
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com