通过ES6 封装了一个上传文件的方法 XMLHttpRequest() 通用
### 上传进度回显,上传速度回显
### 源码如下,新建index.js装起来
export class UploadServers {
constructor (options) {
this.xhr = null
this.startTime = null
this.startFileSize = 0
this.formData = null
// this = options
Object.keys(options).map(item => {
this[item] = options[item]
})
this.init(options)
}
init (options) {
this.config = {...this.config, ...options}
this.xhr = new XMLHttpRequest()
this.formData = new FormData()
if (this.config.data && Object.prototype.toString.call(this.config.data) === '[object Object]') {
// 循环添加其他参数
this.config.data.keys(item => {
this.formData.append(item, this.config.data[item])
})
}
// console.log(this.config)
// console.log(this.config.file.toString())
// console.log(Array.prototype.slice.call(this.config.file).toString())
if (this.config.file.toString() === '[object FileList]' || this.config.file.toString() === '[object File]' || this.config.file.toString() === '[object Array]' || this.config.file.toString().includes('[object File]')) {
this.uploadFile(this.config.file, true)
} else {
this.uploadFile(this.config.file)
}
}
uploadFile (file, isArray) {
// this.xhr
const _this = this
if (isArray) {
Object.values(file).forEach(function (item) {
_this.formData.append(_this.config.uploadFileName, item)
})
} else {
this.formData.append(this.config.uploadFileName, file)
}
this.xhr.open('post', this.config.url, true)
this.xhr.onload = function (e) {
_this.updataSucess(e)
}
this.xhr.onerror = function (e) {
_this.updataError(e)
}
this.xhr.upload.onprogress = function (e) {
_this.progressChange(e)
}
this.xhr.upload.onloadstart = function (e) {
_this.startUpload(e)
}
this.xhr.send(this.formData)
}
startUpload (e) {
// console.log(e)
this.startTime = new Date().getTime()
this.startFileSize = 0
}
updataSucess (e) {
// console.log(e)
// console.log(this)
// console.log(uploadServers)
this.config.success(e)
}
updataError (e) {
console.log(e)
this.config.error(e)
}
progressChange (e) {
// console.log(e)
if (e.lengthComputable) {
const newTime = new Date().getTime()
let pertime = (newTime - this.startTime) / 1000
// 如果时间为0 则返回避免出现Infinity 兼容IOS进度函数读取过快问题
if (pertime === 0) pertime = 0.001
this.startTime = newTime
const perload = e.loaded - this.startFileSize
const lave = e.loaded / e.total
this.startFileSize = e.loaded
let speed = perload / pertime
// console.log(perload, pertime)
// const speeds = speed
let units = 'b/s'
if (speed / 1024 > 1) {
speed = speed / 1024
units = 'k/s'
}
if (speed / 1024 > 1) {
speed = speed / 1024
units = 'M/s'
}
if (speed / 1024 > 1) {
speed = speed / 1024
units = 'G/s'
}
// console.log(speed)
speed = speed.toFixed(1)
// console.log(speed)
// const resout = ((e.total - e.loaded) / speeds).toFixed(1)
this.config.progress(e, speed, lave, e.loaded, units)
}
}
}
使用方式
let initUploadFileChange = new UploadServers({
url: _this.url,
data: _this.data,
file: fileList || null,
fileClassName: null,
uploadFileName: _this.fileOption || 'multipartFiles',
progress: function (e, speed, lave, loaded, units) {
// console.log(e, speed, lave, loaded, units)
_this.percentage = parseInt(lave * 100)
},
success: function (e) {
if (e.target.status === 200 && e.target.response) {
const parseJson = JSON.parse(e.target.response)
}
// 设置状态为未上传状态
_this.processStatus = false
},
error: function (e) {
// 上传失败 应将文件通过File流读取出来进行回显 并展示给用户提示上传失败 请重新上传 或者自动重新上传
_this.processStatus = false
}
})
####
####
END
####
####
通过ES6 封装了一个上传文件的方法 XMLHttpRequest() 通用的更多相关文章
- 朋友封装的一个ASP.NET上传文件的方法
朋友做了asp.net开发多年,做了这个,自我感觉封装得还不错!!! 代码如下: #region 上传文件的方法 /// <summary> /// 上传文件方法 /// </sum ...
- MUI上传文件的方法
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- 以一个上传文件的例子来说 DistributedFileSystem
public class UploadAndDown { public static void main(String[] args) { UploadAndDown uploadAndDown = ...
- web 中常用的两种上传文件的方法总结
这里我们来总结整理一下常用的两种文件上传方式以及要注意的东西: 1.springmvc .MultipartFile 的上传方式. 2.org.apache.commons.fileupload 使用 ...
- IE input file隐藏不能上传文件解决方法
当大神们都在探讨更深层次的问题时,我还在这里转载发些肤浅的问题解决方案.罢了,为了和我一样笨的后来人. 问题: 上传文件时,用<input type="file" /> ...
- 使用jquery插件uploadify上传文件的方法与疑问
我是学生一枚,专业也不是计算机,但又要用到很多相关技术,所以在技术基础不牢靠的情况下,硬着头皮在做.最近在做一个小项目需要上传图片,而且是需要用ajax的方式.但是利用jquery的ajax方法总会有 ...
- Springboot实现上传文件接口,使用python的requests进行组装报文上传文件的方法
记录瞬间 近段时间使用Springboot实现了文件的上传服务,但是在使用python的requests进行post上传时,总是报错. 比如: 1.Current request is not a m ...
- uni-app开发的应用(小程序,app,web等),使用Node+Koa2开发的后端程序接收上传文件的方法
uni-app使用使用Node+Koa2开发的后端程序接收上传的文件 通过gitbook浏览此随笔 通过其它客户端上传(h5,小程序等),接收方法一致 使用koa接收时,我们需安装一个中间件koa-b ...
- python通过http(multipart/form-data)上传文件的方法
之前写过一篇博客,说的如何python如何通过http下载文件,今天写一篇博客来介绍如下,python如何通过request库实现上传文件 这里主要是解决multipart/form-data这种格式 ...
随机推荐
- UVA - 1608 Non-boring sequences (分治)
题意:如果一个序列的任意连续子序列中至少有一个只出现一次的元素,则称这个序列式为non-boring.输入一个n(n≤200000)个元素的序列A(各个元素均为109以内的非负整数),判断它是否无聊. ...
- linux下anaconda的安装和使用
1.将python3设置为默认 直接执行这两个命令即可: sudo update-alternatives --install /usr/bin/python python /usr/bin/pyth ...
- 51nod 1065:最小正子段和
1065 最小正子段和 基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题 收藏 取消关注 N个整数组成的序列a[1],a[2],a[3],-,a[n],从中选出一 ...
- GNS3 模拟icmp分片不可达
R1 : conf t int f0/0 no shutdown ip add 192.168.1.1 255.255.255.0 no ip routing end R2 f0/0: conf t ...
- 概率图模型之EM算法
一.EM算法概述 EM算法(Expectation Maximization Algorithm,期望极大算法)是一种迭代算法,用于求解含有隐变量的概率模型参数的极大似然估计(MLE)或极大后验概率估 ...
- redis3.2.2 集群
http://blog.csdn.net/imxiangzi/article/details/52431729 http://www.2cto.com/kf/201701/586689.html me ...
- servlet中urlpatterns注意事项
在servlet中, @WebServlet(urlPatterns="/newsAdd")接收 resp.sendRedirect("/wedding/houtai/N ...
- 五十四、SAP中LVC表格每列的宽度自适应
一.之前我们的LVC表格输出的界面,有些列太宽余留空白区块太多,有些列则显示不全还带省略号等 二.我们来到'REUSE_ALV_GRID_DISPLAY_LVC'的模块中,查看他的属性 三.我们查看L ...
- office组件导入导出常见异常记录
异常:未能加载文件或程序集"Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken ...
- HDU 3397 线段树 双懒惰标记
这个是去年遗留历史问题,之前思路混乱,搞了好多发都是WA,就没做了 自从上次做了大白书上那个双重懒惰标记的题目,做这个就思路很清晰了 跟上次大白上那个差不多,这个也是有一个sets标记,代表这个区间全 ...