原理:

jquery form插件ajax上传文件的原理,

1、浏览器实现了XMLHttpRequest level2规范的,则插件使用xhr直接提交文件。通常来说chrome、firefox都实现了xhr level2规范

2、浏览器只实现了XMLHttpRequest level1规范的,则插件使用form+iframe方式,实现页面无刷新上传文件。通常来说,IE8及以下都属于此列。

有关form+iframe方式实现的页面无刷新文件上传,请参考博文form+iframe仿ajax上传文件

jquery form上传文件的样例代码

html代码

<div><h2>jquery form插件上传文件 - 示例程序</h2><form id="uploadForm" method="post" ><input type="file" name="Filedata"></input><input id="subbtn" type="submit" ></form> </div>

js代码

$('input[name=Filedata]').change(function () {initUploadForm();
});function initUploadForm () {var url = "/flash/upload";var options = { type: 'post',url: url,success:function(ret) { //var tempret = eval('('+ret+')');alert(tempret.result);},error:function (responseText, statusText) {alert("shang chuan cuo wu");}}; // pass options to ajaxForm $('#uploadForm').ajaxForm(options);
}

后续问题:

上述代码在chrome下运行没有问题,在IE8浏览器下提示“下载json文件”。通过查阅资料得知,IE8下会使用form+iframe方式提交文件,因为iframe只识别html和xml,所以当服务器端返回的内容类型是application/json时,iframe不识别,浏览器提示下载,故要求IE8浏览器下,服务器端返回内容类型必须是text/html

修正:

服务器端,根据客户端是否是ajax请求,来分别设置Content-Type,比如

String ajaxmethod = request.getHeader("X-Requested-With");if(StringUtils.isBlank(ajaxmethod)){//非ajax请求response.setContentType("text/html;charset=UTF-8");}else{response.setContentType("application/json;charset=UTF-8");}
Map<String,String>  map = new HashMap<String,String> ();map.put("result", "success");String jsonstr = new Gson().toJson(map);try {response.getWriter().write(jsonstr);} catch (IOException e) {e.printStackTrace();} 

客户端,如果仅仅设置服务器端,客户端又会出问题。在IE8下会出现undefined,究其原因是success函数接收的参数是json字符串,没有转化为json 对象,所以,alert(ret.result)时,ret还是json串,ret.result值就是undefined。

解决方案就是,在客户端判断,返回值是否是json字符串,返回值是json字符串,就进行转换。返回值不是json字符串,就不再进行转换;

if(typeof ret == "string"){var tempret = eval('('+ret+')');alert(tempret.result);}else{alert(ret.result);}

jquery form上传文件原理原文:

htmlExampleTarget (output will be added below):

This page demonstrates the Form Plugin's file upload capabilities. There is no special coding required to handle file uploads. File input elements are automatically detected and processed for you.

Browsers that support the XMLHttpRequest Level 2 will be able to upload files seamlessly and even get progress updates as the upload proceeds. For older browsers, a fallback technology is used which involves iframes since it is not possible to upload files using the level 1 implmenentation of the XMLHttpRequest object. This is a common fallback technique, but it has inherent limitations. The iframe element is used as the target of the form's submit operation which means that the server response is written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the response type is script or JSON, both of which often contain characters that need to be repesented using entity references when found in HTML markup.

To account for the challenges of script and JSON responses when using the iframe mode, the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads and older browsers.

It is important to note that even when the dataType option is set to 'script', and the server is actually responding with some javascript to a multipart form submission, the response's Content-Type header should be forced to text/html, otherwise Internet Explorer will prompt the user to download a "file".

Also note that if there is no file input in the form then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your server code to know when to use a textarea and when not to. If you like, you can use the iframe option of the plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea. But the recommended solution is to test for the 'X-Requested-With' request header. If the value of that header is 'XMLHttpRequest' then you know that the form was posted via ajax. The following PHP snippet shows how you can be sure to return content successfully:

参考资料:

jquery form Plugin doc

jquery form插件(ajax)上传文件实现及原理相关推荐

  1. jquery form java_springmvc利用jquery.form插件异步上传文件示例

    需要的下载文件: jQuery.form.js jquery.js commons-fileupload.jar commons-io.jar 示例图片 pom.xml commons-fileupl ...

  2. 6.jQuery中的Ajax上传文件

    目录 1  上传文件 2  loading效果 1  上传文件 后端接到数据后保存在upload_file文件夹下 前端依然使用FormData处理文件 contentType:false的意思是 使 ...

  3. day059-60 ajax初识 登录认证练习 form装饰器, form和ajax上传文件 contentType

    一.ajax 的特点 1.异步交互:客户端发出一个请求后,需要等待服务器响应结束后, 才能发出第二个请求 2.局部刷新:给用户的感受是在不知不觉中完成请求和响应过程. 二.ajax 模板示例 ($.a ...

  4. flask ajax 上传 图片,flask jQuery ajax 上传文件

    1.html 代码 注:1.html 部分主要是一个form表单,其中表单的enctype = "multipart/form-data" 必须要有. 2.由于我的页面背景颜色设置 ...

  5. egg.js ajax上传文件,egg.js 通过 form 和 ajax 两种方式上传文件并自定义目录和文件名...

    一.需求 egg.js 的文件上传个人觉得很一般,内置的 multipart 插件并不怎么好用. egg-multipart 也是基于 co-busboy 实现的. egg 官方给的文件上传的示例地址 ...

  6. jsp通过ajax上传文件,基于jquery

    #前言 推荐讲解:使用ajax提交form表单,包括ajax文件上传 推荐讲解:HTML5+Ajax上传文件 建议:看这篇之前,请先了解直接form表单提交servlet方式上传文件  jsp上传文件 ...

  7. Jquery+ajax上传文件

    前言: 之前做文件操作都是直接通过表单提交的,这几天做了一个前台用jquery+ajax上传文件,后台用MVC接受文件,由于第一次用jquery+ajax做上传文件,所以用来写个博客.方便以后直接用. ...

  8. ajax ashx 请选择文件,ajax+jquery+ashx如何实现上传文件

    ajax+jquery+ashx如何实现上传文件 第一:建立Default.aspx页面 ajax图片上传 function upload(){ var path = document.getElem ...

  9. Django框架 之 Form表单和Ajax上传文件

    Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...

最新文章

  1. 关于struts2如何去掉默认的后缀(.action)
  2. 加减法叫做什么运算_小学四则运算基础知识,赶快给孩子存下吧!
  3. 【ASP.NET Core】处理异常
  4. String s = new String(xyz);创建了几个对象?
  5. 你觉得iPhone吸引你的是什么?
  6. 理解Load Average做好压力测试
  7. SpringBoot-JPA删除不成功,只执行了查询语句
  8. Java中类的创建及类与对象的关系
  9. left和offsetLeft
  10. Django+MySQLDB配置
  11. journalctl日志工具使用方法
  12. R语言mad函数、median函数、mean函数计算中位数绝对偏差、中位数、均值实战
  13. 前端实现对ZIP 压缩文件解压,实现前端直接展示结果,比如图片,压缩包等 audio对象进行播放
  14. 临近毕业,图像类SCI源刊哪本审稿快?
  15. 微信公众号最新留言评论管理功能怎么开通获取?(内附留言功能开通视频链接)
  16. 光场相机预处理 TFTOOLBOX
  17. 微信小程序即将上线,现在就可以开发啦
  18. 算法题:最少出牌次数
  19. Maven安装和配置阿里云镜像(解决在idea中Maven加载依赖慢的问题,保姆级教学)
  20. css自定义字体font-face的兼容和使用

热门文章

  1. 【Python】基础知识整理
  2. 如何优雅地通过绿X科技的Web安全漏洞扫描
  3. JavaScript 开发者应懂的 33 个概念
  4. 元宇宙“扫地僧”潘志庚教授:要有开放的态度,拥抱元宇宙
  5. 日货列表,经常看看,坚决抵制日货
  6. ShareX - 功能强大、免费开源的 Windows 截图录屏工具,支持 OCR 识别和滚动截图等多种功能
  7. 如何理解“凡所有相,皆是虚妄,若见诸相非相,即见如来”--短句摘抄
  8. 1.#_5 macbook pro入门(M1)
  9. 【react 报错】Failed to parse source map
  10. sparksteaming---实时流计算Spark Streaming原理介绍