使用 jQuery 的 AJAX 异步上传文件

2022-12-22 0 571

那时大体上上许多页面里头都在采用 jQuery,要同时实现文档的促发器上载,绝大多数的化解方式都是采用 jQuery 应用程序,假如你而已上载两张相片,采用应用程序反倒真的累赘了,只但是 jQuery 的 ajax() 方式是能同时实现文档上载的,但是他们平常大体上采用 get() 和 post() 方式,ajax() 方式反倒采用的极少,上面给我们撷取采用 jQuery 的 AJAX 促发器上载文档。

使用 jQuery 的 AJAX 异步上传文件

虽然是 AJAX 异步上载,因此他们大体上不须要 form 条码,只须要两个 file 的类型信息。

<input type=”hidden” name=”store_avatar” class=”store_avatar” value=”” /><input type=”file” name=”upload_file” class=”upload_file” style=”display:none; ” /><button type=”button” class=”btn btn-primary btn-xs profile_avatar_btn”>上载相片</button><p>请上载你的店面LOGO,全力支持 JPG、PNG 和 GIF 文件格式。</p>

这儿为的是介面漂亮,他们把 file 类型信息暗藏,采用两个自订的按键来促发优先选择文档的操作方式,具体文本的操作方式是当使用者点选按键的这时候,采用 JS 的 trigger() 触发 file 的点选该事件。

$(.profile_avatar_btn).click(function(){ $(this).parents(td).find(.upload_file).trigger(click);})

当 file 类型信息的文本发生改变的这时候,也是使用者优先选择了文档,他们存取他们的自订标识符:

$(.upload_file).change(function(){ //code})

接下去就须要校正文档,即使使用者优先选择的可能将不是他们须要的文档类型

file_item = $(this).get(0).files[0];if(file_item.size > 2 * 1024 * 1024){ $(.profile_avatar_btn).attr(title, 文档太大).tooltip(show); return false;}if(!(file_item.type == “image/jpeg” || file_item.type == “image/gif” || file_item.type == “image/png”)){ $(.profile_avatar_btn).attr(title, 优先选择的文档不是相片).tooltip(show); return false;}

假如上面的校正程序都通过了,那么他们开始上载文档

var formData = new FormData();formData.append(“upload_file”, file_item);$(.profile_avatar_btn).html(<i class=”fa fa-refresh fa-spin”></i> 上载中);this_input = $(this);$.ajax({ url: “/seller/shop-setting/”, type: POST, cache: false, data: formData, processData: false, contentType: false, dataType:”json”, beforeSend: function(){ uploading = true; }, success:function(data) { if (data.code == 1) { $(.store_avatar).val(data.msg); $(.profile_avatar img).attr(src, data.msg); $(.profile_avatar_btn).html(重新上载); } uploading = false; }});

其中关键要素:

contentType:application/x-www-form-urlencoded

发送信息至服务器时文本编码类型。默认值适合绝大多数情况。假如你明确地传递了两个 content-type 给 $.ajax() 那么他必定会发送给服务器(即使没有数据要发送)

processData:true

默认情况下,通过 data 选项传递进来的数据,假如是两个对象(技术上讲只要不是字符串),都会处理转化成两个查询字符串,以配合默认文本类型 application/x-www-form-urlencoded。假如要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

FormData

XMLHttpRequest Level 2 添加了两个新的接口 FormData 利用 FormData 对象,他们能通过 JavaScript 用一些键值对来模拟一系列表单控件,我们还能采用 XMLHttpRequest 的 send() 方式来促发器的提交这个表单,比起普通的 ajax,采用 FormData 的最大优点是他们能促发器上载两个二进制文档。

举报/反馈

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务