1. 程式人生 > >圖片上傳顯示進度條和預覽圖的前端實現之進度條篇

圖片上傳顯示進度條和預覽圖的前端實現之進度條篇

很久沒有寫部落格了,是最近忙著找實現,另外工作也很忙,閒下來整理一下最近做的東西,覺得還是有點可寫的。
不知道有沒有朋友在工作中碰到這樣的需求,需要實現一個元件,能實現圖片上傳功能,同時,在圖片未上傳完成時,要顯示進度條和相應的圖片預覽圖
如圖所示,上傳過程中,進度條和預覽圖都能顯示:進度條

這一篇首先來說說點選上傳功能和進度條功能的實現吧,等今天忙完了我繼續更新下一篇

點選彈出資料夾,選擇上傳的功能想必我不說很多朋友即使沒接觸過也有所瞭解,就是要依靠<input type="file"> ,當然也可以指定accept來制定只允許上傳某些型別的檔案,比如圖片你可以指定只允許accept="image/jpeg,image/jpg,image/png,image/x-png,image/gif"


至於進度條事件就依賴於progressEvent物件來實現,progressEvent實際上在XMLHttpRequest物件的progress事件和loaded事件都能通過event訪問到,可以認為它繼承了Event物件並擴充套件了一些屬性。
我們不妨來看看這些要處理進度條事件時要用到的屬性吧:

ProgressEvent.lengthComputable
Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

ProgressEvent.loaded
Is an unsigned long long representing the amount of work already performed by the underlying process. The ratio of work done can be calculated with the property and ProgressEvent.total. When downloading a resource using HTTP, this only represent the part of the content itself, not headers and other overhead.

ProgressEvent.total
Is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this only represent the content itself, not headers and other overhead.

很明白了有木有,第一個屬性lengthComputable主要表明總共需要完成的工作量和已經完成的工作是否可以被測量,如果返回是false意味著很遺憾,之後的ProgressEvent.total和loaded估計是出不了確定的值了,也就是說,咱們的進度條效果恐怕要吹了,不過還好,一般情況下他都是true,也就是後面兩個值是能拿到的,那麼就比較好辦啦。 如果你很關注,什麼情況下lengthComputable可能會變成false,可以敲下這裡看看。 第二個第三個屬性就是咱們要用來處理進度條的方法啦。ProgressEvent.loaded 代表當前已經上傳完成的,ProgressEvent.total則是全部,這不就很簡單啦,loaded/total得到相應的比例,咱們的進度條就有了是不是!

一個簡單的實現如下

let progressBar = document.getElementById("p"),
    client = new XMLHttpRequest()
    client.open("GET", "xxx/xxx")
client.onprogress = function(e) {
    if (e.lengthComputable) {
      let total = e.total;
      let loaded = e.loaded;
      let percentage = Math.floor(total/loaded);
      progressBar.style.width = `${percentage}%`
    }
  }
client.send()

假定progressBar對應的p元素外面包裹了一層div並設定了width,設定內層的百分比即可,當然,也可以藉助background-position來實現。
先寫到這啦,趕緊幹活去了,關於預覽圖的實現將在下一篇介紹!