×

点击文件上传jquery

点击文件上传jquery(jquery上传文件到后端)

admin admin 发表于2023-03-25 10:28:08 浏览61 评论0

抢沙发发表评论

本文目录一览:

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

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(); } }); -点击文件上传jquery

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

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

更多用法可以 参考官网

使用jquery-form的FormData上传文件带参数

html示例内容如下:

直接使用FormData提交文件的话,不带参数可以用下面的方法:

FormData的数据会自动组织成multipart/form-data形式的,因此不需要JQuery进行转化了,因此contentType,processData为false。

但是上面这种方法不适合带参数的,如果上传还要求带上参数的话,可以使用如下方法:

这种方法带上参数了,而文件的参数名为input type="file" name="file"中定义的name名,要修改参数名只需要在这里name名。

使用jquery上传文件

核心原理

1、点击按钮后讲file存为变量,创建FromData对象,讲file追加到fd里面;

2、发起ajax请求,将fd传送到指定的接口;

3、当服务器回应数据时,使用attr方法修改图片URL,将图片文件显示到页面中;

3、发起ajaxStart事件,监听到ajax请求发起时,显示loading;

3、发起ajaxStop事件,监听到ajax请求结束时,关闭loading;

HTML

JS

jquery升级后,上传的文件无效

升级后文件类型不匹配,无法上传。

在 IE8/9 中使用 JQuery 上传只能使用 Form 的方式。

使用 JQuery.Ajax 无法上传文件(因为无法使用 FormData,FormData 是 HTML5 的一个特性,IE8/9 不支持)

使用 JQuery Form 上传,contentType 只能为 text/html,因为如果是 application/json 类型,IE8/9 会以文件下载的方式展现 json 数据。