首页 > 语言 > JavaScript > 正文

jQuery Ajax使用FormData对象上传文件的方法

2024-05-06 15:45:49
字体:
来源:转载
供稿:网友

FormData是表单数据我们用来提交表格的数据,FormData对象允许我们对表单数据进行操作,下面错新技术频道小编给大家分享jQuery Ajax使用FormData对象上传文件的方法吧!

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

HTML代码

<form id="uploadForm" enctype="multipart/form-data"><input id="file" type="file" name="file"/><button id="upload" type="button">upload</button></form>

javascript代码

$.ajax({url: '/upload',type: 'POST',cache: false,data: new FormData($('#uploadForm')[0]),processData: false,contentType: false}).done(function(res) {}).fail(function(res) {});

这里要注意几点:

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代码

<div id="uploadForm"><input id="file" type="file"/><button id="upload" type="button">upload</button></div>

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

var formData = new FormData();formData.append('file', $('#file')[0].files[0]);$.ajax({url: '/upload',type: 'POST',cache: false,data: formData,processData: false,contentType: false}).done(function(res) {}).fail(function(res) {});

这里有几处不一样:

append()的第二个参数应是文件对象,即$('#file')[0].files[0]。

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

后台接收文件:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"/></bean>@RequestMapping(value = "/import_tg_resource")public ModelAndView import_tg_resource(@RequestParam(value = "file", required = false) MultipartFile[] files, HttpServletRequest request, ModelMap model) {System.out.println("开始批量上传:文件数量:" + files.length);for (MultipartFile file : files ) {String path = request.getSession().getServletContext().getRealPath("upload");String fileName = file.getOriginalFilename();String prefix = fileName.substring(fileName.lastIndexOf("."));fileName = new Date().getTime() + prefix;// System.out.println("保存路径 " + path);File targetFile = new File(path, fileName);if(!targetFile.exists()){targetFile.mkdirs();}file.transferTo(targetFile);}}

以上就是错新技术频道小编分享的jQuery Ajax使用FormData对象上传文件的方法,看完后你感觉有不懂的地方吗?如果有疑问就请联系我们。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选