经过jQuery Ajax使用FormData对象上传文件

FormData对象,是能够使用一系列的键值对来模拟一个完整的表单,而后使用XMLHttpRequest发送这个"表单"。 在 Mozilla Developer 网站 使用FormData对象 有详尽的FormData对象使用说明。 但上传文件部分只有底层的XMLHttpRequest对象发送上传请求,那么怎么经过jQuery的Ajax上传呢? 本文将介绍经过jQuery使用FormData对象上传文件。javascript

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

HTML代码java

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

javascript代码web

$.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>标签添加enctype="multipart/form-data"属性。spring

  • cache设置为false,上传文件不须要缓存。
  • contentType设置为false。由于是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",因此这里设置为false。

上传后,服务器端代码须要使用从查询参数名为file获取文件输入流对象,由于<input>中声明的是name="file"。 若是不是用<form>表单构造FormData对象又该怎么作呢?缓存

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

HTML代码app

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

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

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);
        }
    }
相关文章
相关标签/搜索