使用jquery.form.js实现文件上传及进度条前端代码

JavaScript010

使用jquery.form.js实现文件上传及进度条前端代码,第1张

ajax的表单提交只能提交data数据到后台,没法实现file文件的上传还有展示进度功能,这里用到form.js的插件来实现,搭配css样式简单易上手,而且高大上,推荐使用。

需要解释下我的结构, #upload-input-file 的input标签是真实的文件上传按钮,包裹form标签后可以实现上传功能, #upload-input-btn 的button标签是展示给用户的按钮,因为需要样式的美化。上传完成生成的文件名将会显示在 .upload-file-result 里面, .progress 是进度条的位置,先让他隐藏加上 hidden 的class, .progress-bar 是进度条的主体, .progress-bar-status 是进度条的文本提醒。

去掉hidden的class,看到的效果是这样的

[图片上传失败...(image-2c700a-1548557865446)]

将上传事件绑定在file的input里面,绑定方式就随意了。

var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'//上传步骤 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden")progress.width(percentVal)status.html(percentVal)}, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'progress.width(percentVal)status.html(percentVal)console.log(percentVal, position, total)}, success: function (result) { percentVal = '100%'progress.width(percentVal)status.html(percentVal)//获取上传文件信息 uploadFileResult.push(result)// console.log(uploadFileResult)$(".upload-file-result").html(result.name)$("#upload-input-file").val('')}, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown)$(".upload-file-result").empty()} })

[图片上传失败...(image-3d6ae0-1548557865446)]

[图片上传失败...(image-9f0adf-1548557865446)]

更多用法可以 参考官网

1、将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率。

2、异步上传文件

1、创建一个空对象:

2、通过表单对formData进行初始化

创建表单:

通过表单元素作为参数,实现对formData的初始化:

1、通过get(key)与getAll(key)来获取相对应的值

2、通过append(key,value)在数据末尾追加数据

3、通过set(key, value)来设置修改数据

key的值不存在,会添加一条数据

key的值存在,会修改对应的value值

4、通过has(key)来判断是否存在对应的key值

5、通过delete(key)可以删除数据

创建表单:

发送数据: