vue中使用axios post上傳頭像/圖片並即時顯示到頁面

來源:互聯網
上載者:User

標籤:pre   bsp   headers   開發   route   vue   params   eve   方法   

前端開發中,為了更好的使用者體驗,在頭像上傳時會先將圖片顯示到頁面然後點擊儲存按鈕 完成圖片的上傳成功 代碼部分有參考他人的寫法。

html代碼:

 <div id="myPhoto" v-show="personalPhoto">        <div class="viewPhoto">          <img src="" alt="" id="portrait"style="width: 300px;height: 300px" />        </div>        <div class="listBox">          <dl>            <dt>請上傳圖片</dt>            <dd>              <input type="file"id="saveImage" name="myphoto" >            </dd>          </dl>        </div>        <div class="save">          <input type="button"  value="儲存圖片" @click="imageSubmit">        </div>      </div>

js代碼:

//即時顯示該圖片在頁面 great(){          document.getElementById(‘saveImage‘).onchange = function () {          var imgFile = this.files[0];         // this.file = event.target.files[0];          var fr = new FileReader();          fr.onload = function () {            document.getElementById(‘portrait‘).src = fr.result;          };          fr.readAsDataURL(imgFile);          }        },

js代碼部分說明:因為是在vue的methods方法中申明的函數,所以還需要在mounted 方法中使用this.great()掛載該方法。

圖片上傳部分的js代碼:

imageSubmit(){          let x = document.getElementById(‘saveImage‘).files[0];          console.log(x);          let params = new FormData() ; //建立一個form對象          params.append(‘file‘,x,x.name);  //append 向form表單添加資料          //添加要求標頭  通過form添加的圖片和檔案的格式必須是multipart/form-data          let config = {            headers:{‘Content-Type‘:‘multipart/form-data‘}          };          this.$axios.post("/user/image",params,config)            .then(function(res){              console.log(res);              this.imageSave = res.data.image;              sessionStorage.setItem(‘headImg‘,this.imageSave); //將圖片儲存,並能夠在其他地方載入顯示              router.go(0);   //重新整理頁面,頭像改變            }.bind(this))            .catch(function (error) {              console.log(error);            })        }      },

註:在後來的開發過程中發現,上傳圖片在上傳伺服器前在頁面載入可以使用

var windowURL = window.URL || window.webkitURL;

vue中使用axios post上傳頭像/圖片並即時顯示到頁面

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.