图片上传显示进度条和预览图的前端实现之进度条篇

来源:互联网 发布:sql server字符串类型 编辑:程序博客网 时间:2024/06/09 21:45

很久没有写博客了,是最近忙着找实现,另外工作也很忙,闲下来整理一下最近做的东西,觉得还是有点可写的。
不知道有没有朋友在工作中碰到这样的需求,需要实现一个组件,能实现图片上传功能,同时,在图片未上传完成时,要显示进度条和相应的图片预览图
如图所示,上传过程中,进度条和预览图都能显示:进度条

这一篇首先来说说点击上传功能和进度条功能的实现吧,等今天忙完了我继续更新下一篇

点击弹出文件夹,选择上传的功能想必我不说很多朋友即使没接触过也有所了解,就是要依靠<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来实现。
先写到这啦,赶紧干活去了,关于预览图的实现将在下一篇介绍!

阅读全文
0 0
原创粉丝点击