通过Ajax使用FormData对象无刷新上传文件

http://blog.csdn.net/z69183787/article/details/52526412

写在前面:本文说的这个方案有浏览器兼容性问题;所有主流浏览器的较新版本已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+,对兼容性比较敏感的网站慎用。

 

在工作中遇到了一个问题:在一个页面中,有4块内容,每块内容都包含一个图片上传功能,希望可以实现一键把这四块内容都上传上去。

我没有用插件实现上传功能,就是用的input[type=file],因此就遇到一个问题就是:

  ①传统的form表单会导致页面刷新,无法实现上述功能

  ②把表单serialize()序列化用Ajax的方式提交,也无法把上传文件的文件流进行序列化,也不行

我现有的知识就搞不定了,只能求助网上的大神了,百度了一下,大概看了两个方案:

  ①在js中创建一个新form表单,把页面中原form表单copy一份,然后再用js搞一个iframe,把form表单的target设置为iframe,这样提交后返回的内容就在iframe里,最后再把form表单、iframe移除

    该方案我没有尝试,只能说个大概;参考地址:http://www.oschina.net/code/snippet_569983_11316

  ②就是本文下面要说的使用FormData对象实现

有其他思路方案的希望不吝赐教! 

 

好,介绍完背景之后,开始介绍我们今天的主题:FormData对象。

有两种方式可以创建一个FormData对象:

  ①创建一个空的FormData对象,然后使用append()方法向该对象里添加字段

  ②使用HTML表单来初始化一个FormData对象

下面分别介绍一下:

  第一种方式:

复制代码
var oMyForm = new FormData();
oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); 
oMyForm.append("file", $('#file')[0].files[0]);

$.ajax({
    url: '/Manage/UploadImg',
    type: 'POST',
    cache: false,
    data: oMyForm,
    processData: false,
    contentType: false,
    async: false
}).done(function(res) {}).fail(function(res) {});
复制代码

  第二种方式:

<form id="uploadForm" enctype="multipart/form-data">
    <p>指定文件名: <input type="text" name="filename" value="" /></p>
    <p>上传文件: <input type="file" name="file" /></ p>
        <input type="button" value="上传" onclick="doUpload()" />
</form>

 

复制代码
var formData = new FormData($('#uploadForm')[0]);
formData.append('num', '1');//可以在已有表单数据的基础上,继续添加新的键值对
$.ajax({
    url: '/upload',
    type: 'POST',
    cache: false,
    data: new FormData($('#uploadForm')[0]),
    processData: false,
    contentType: false
}).done(function(res) {}).fail(function(res) {});
复制代码

 

注意:

  • Ajax的processData设置为false。因为data值是FormData对象,不需要对数据做处理。
    • 第二种方式中<form>标签加enctyp  e="multipart/form-data"属性。
  • cache设置为false,上传文件不需要缓存。
  • contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="mutipart/form-data",所以这里设置为false。

 

前端搞定之后,剩下的就是后端处理了。ok,就到这里了。


FormData对象,是可以使用一系列的键值对来模拟一个完整的表单,然后使用XMLHttpRequest发送这个"表单"。

在 Mozilla Developer 网站 使用FormData对象 有详尽的FormData对象使用说明。

但上传文件部分只有底层的XMLHttpRequest对象发送上传请求,那么怎么通过jQueryAjax上传呢?
本文将介绍通过jQuery使用FormData对象上传文件。

使用<form>表单初始化FormData对象方式上传文件

HTML代码

<code class="xml"><span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">form</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"uploadForm"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">enctype</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"multipart/form-data"</span>></span>
    <span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">input</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"file"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">type</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"file"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">name</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"file"</span>/></span>
    <span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">button</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"upload"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">type</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"button"</span>></span>upload<span class="hljs-tag" style="color: rgb(0, 102, 102);"></<span class="hljs-title" style="color: rgb(0, 0, 136);">button</span>></span>
<span class="hljs-tag" style="color: rgb(0, 102, 102);"></<span class="hljs-title" style="color: rgb(0, 0, 136);">form</span>></span></code>

JavaScript代码

<code class="javascript">$.ajax({
    url: <span class="hljs-string" style="color: rgb(0, 136, 0);">'/upload'</span>,
    type: <span class="hljs-string" style="color: rgb(0, 136, 0);">'POST'</span>,
    cache: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>,
    data: <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> FormData($(<span class="hljs-string" style="color: rgb(0, 136, 0);">'#uploadForm'</span>)[<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>]),
    processData: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>,
    contentType: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>
}).done(<span class="hljs-function"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">function</span>(<span class="hljs-params" style="color: rgb(102, 0, 102);">res</span>) </span>{
}).fail(<span class="hljs-function"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">function</span>(<span class="hljs-params" style="color: rgb(102, 0, 102);">res</span>) </span>{});</code>

这里要注意几点:

  • processData设置为false。因为data值是FormData对象,不需要对数据做处理。
  • <form>标签添加enctype="multipart/form-data"属性。
  • cache设置为false,上传文件不需要缓存。
  • contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。

上传后,服务器端代码需要使用从查询参数名为file获取文件输入流对象,因为<input>中声明的是name="file"

如果不是用<form>表单构造FormData对象又该怎么做呢?

使用FormData对象添加字段方式上传文件

HTML代码

<code class="xml"><span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">div</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"uploadForm"</span>></span>
    <span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">input</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"file"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">type</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"file"</span>/></span>
    <span class="hljs-tag" style="color: rgb(0, 102, 102);"><<span class="hljs-title" style="color: rgb(0, 0, 136);">button</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">id</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"upload"</span> <span class="hljs-attribute" style="color: rgb(102, 0, 102);">type</span>=<span class="hljs-value" style="color: rgb(0, 136, 0);">"button"</span>></span>upload<span class="hljs-tag" style="color: rgb(0, 102, 102);"></<span class="hljs-title" style="color: rgb(0, 0, 136);">button</span>></span>
<span class="hljs-tag" style="color: rgb(0, 102, 102);"></<span class="hljs-title" style="color: rgb(0, 0, 136);">div</span>></span></code>

这里没有<form>标签,也没有enctype="multipart/form-data"属性。

javascript代码

<code class="javascript"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">var</span> formData = <span class="hljs-keyword" style="color: rgb(0, 0, 136);">new</span> FormData();
formData.append(<span class="hljs-string" style="color: rgb(0, 136, 0);">'file'</span>, $(<span class="hljs-string" style="color: rgb(0, 136, 0);">'#file'</span>)[<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>].files[<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>]);
$.ajax({
    url: <span class="hljs-string" style="color: rgb(0, 136, 0);">'/upload'</span>,
    type: <span class="hljs-string" style="color: rgb(0, 136, 0);">'POST'</span>,
    cache: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>,
    data: formData,
    processData: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>,
    contentType: <span class="hljs-literal" style="color: rgb(0, 102, 102);">false</span>
}).done(<span class="hljs-function"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">function</span>(<span class="hljs-params" style="color: rgb(102, 0, 102);">res</span>) </span>{
}).fail(<span class="hljs-function"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">function</span>(<span class="hljs-params" style="color: rgb(102, 0, 102);">res</span>) </span>{});</code>

这里有几处不一样:

  • append()的第二个参数应是文件对象,即$('#file')[0].files[0]
  • contentType也要设置为‘false’。

从代码$('#file')[0].files[0]中可以看到一个<input type="file">标签能够上传多个文件,
只需要在<input type="file">里添加multiplemultiple="multiple"属性。

服务器端读文件

Servlet 3.0 开始,可以通过 request.getPart() 或 request.getPars() 两个接口获取上传的文件。
这里不多说,详细请参考官网教程 Uploading Files with Java Servlet Technology 以及示例 The fileupload Example Application

参考



文/Agreal(简书作者)
原文链接:http://www.jianshu.com/p/46e6e03a0d53
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值