使用FormData进行Ajax请求上传文件到controller层的实现

需求背景:

页面上传一个文件到controller层,然后后台对文件进行处理。文件类型不限

第一种:单纯的上传文件

页面功能展现:

第一步:首先需要两个jar

commons-fileupload-1.3.2.jar
commons-io-2.4.jar

版本不限:

pom文件中相应两个jar:

[html] view plain copy

print?

  1. <dependency>
  2. <groupId>commons-io</groupId>
  3. <artifactId>commons-io</artifactId>
  4. <version>2.4</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-fileupload</groupId>
  8. <artifactId>commons-fileupload</artifactId>
  9. <version>1.3</version>
  10. </dependency>
    <dependency>        <groupId>commons-io</groupId>        <artifactId>commons-io</artifactId>        <version>2.4</version>    </dependency>    <dependency>        <groupId>commons-fileupload</groupId>        <artifactId>commons-fileupload</artifactId>        <version>1.3</version>    </dependency>

第二步:在spring-mvc.xml中配置

[html] view plain copy

print?

  1. <!-- 文件上传配置 -->
  2. <bean id="multipartResolver"
  3. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  4. <!-- 上传的最大限制 -->
  5. <property name="maxUploadSize" value="209715200" />
  6. <!-- 默认编码 -->
  7. <property name="defaultEncoding" value="UTF-8" />
  8. <!-- 上传文件的解析 -->
  9. <property name="resolveLazily" value="true" />
  10. </bean>
    <!-- 文件上传配置 -->    <bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <!-- 上传的最大限制 -->        <property name="maxUploadSize" value="209715200" />        <!-- 默认编码 -->        <property name="defaultEncoding" value="UTF-8" />        <!-- 上传文件的解析 -->        <property name="resolveLazily" value="true" />    </bean>

第三步:jsp页面代码

[html] view plain copy

print?

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%@ page isELIgnored="false" %>
  3. <!DOCTYPE HTML>
  4. <html>
  5. <head>
  6. <meta charset="UTF-8" />
  7. <title>数据生成</title>
  8. </head>
  9. <body>
  10. <div>
  11. <form method="post" id="file" action="" enctype="multipart/form-data">
  12. <h3>选择一个文件:</h3>
  13. <input id="excelFile" type="file" name="uploadFile" />
  14. <br/><br/>
  15. <input type="button" value="上传" onclick="uploadFiles();"/>
  16. </form>
  17. </div>
  18. </body>
  19. <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  20. <script>
  21. function uploadFiles(){
  22. //  var uploadFile = $(‘#excelFile‘).get(0).files[0];
  23. var uploadFile = new FormData($("#file")[0]);
  24. console.log(uploadFile);
  25. if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
  26. $.ajax({
  27. url:‘/manage/fileupload/upload‘,
  28. type:‘POST‘,
  29. data:uploadFile,
  30. async: false,
  31. cache: false,
  32. contentType: false, //不设置内容类型
  33. processData: false, //不处理数据
  34. success:function(data){
  35. console.log(data);
  36. alert(data.msg);
  37. },
  38. error:function(){
  39. alert("上传失败!");
  40. }
  41. })
  42. }else {
  43. alert("选择的文件无效!请重新选择");
  44. }
  45. }
  46. </script>
  47. </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page isELIgnored="false" %><!DOCTYPE HTML><html><head>    <meta charset="UTF-8" />    <title>数据生成</title></head><body>    <div>        <form method="post" id="file" action="" enctype="multipart/form-data">            <h3>选择一个文件:</h3>            <input id="excelFile" type="file" name="uploadFile" />            <br/><br/>            <input type="button" value="上传" onclick="uploadFiles();"/>        </form>    </div></body><script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script><script>function uploadFiles(){  //  var uploadFile = $(‘#excelFile‘).get(0).files[0];    var uploadFile = new FormData($("#file")[0]);    console.log(uploadFile);    if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){        $.ajax({            url:‘/manage/fileupload/upload‘,            type:‘POST‘,            data:uploadFile,            async: false,              cache: false,             contentType: false, //不设置内容类型            processData: false, //不处理数据            success:function(data){                console.log(data);                alert(data.msg);            },            error:function(){                alert("上传失败!");            }        })    }else {        alert("选择的文件无效!请重新选择");    }}   </script></html>

有关于FormData可参考此链接:

[html] view plain copy

print?

  1. https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

第四步:controller层代码

[java] view plain copy

print?

  1. package com.bigaoread.platform.web.manage.fileupload;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import javax.servlet.http.HttpServletRequest;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import com.bigaoread.platform.service.fileupload.FileUploadService;
  15. @Controller
  16. @RequestMapping("/manage/fileupload")
  17. public class FileUploadController {
  18. private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
  19. @Autowired
  20. private FileUploadService fileUploadService;
  21. @RequestMapping("/uploadPage")
  22. public String uploadPage() {
  23. return "/manage/fileupload/uploadPage";
  24. }
  25. @RequestMapping(value="/upload", method=RequestMethod.POST)
  26. @ResponseBody
  27. public Map<String, Object> uploadFile(HttpServletRequest request,
  28. @RequestParam MultipartFile uploadFile){
  29. Map<String,  Object> resultMap = new HashMap<>();
  30. resultMap = fileUploadService.uploadFile(uploadFile);
  31. return resultMap;
  32. }
  33. }
package com.bigaoread.platform.web.manage.fileupload;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.bigaoread.platform.service.fileupload.FileUploadService;@[email protected]("/manage/fileupload")public class FileUploadController {    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);        @Autowired    private FileUploadService fileUploadService;        @RequestMapping("/uploadPage")    public String uploadPage() {        return "/manage/fileupload/uploadPage";    }        @RequestMapping(value="/upload", method=RequestMethod.POST)    @ResponseBody    public Map<String, Object> uploadFile(HttpServletRequest request,            @RequestParam MultipartFile uploadFile){        Map<String,  Object> resultMap = new HashMap<>();        resultMap = fileUploadService.uploadFile(uploadFile);        return resultMap;    }}

第五步:debug测试

上传文件 表结构原始.docx

点击上传后,后台debug查看对象:

上传成功!

第二种,假如在前端还要传入其他参数时的做法

情景图(增加了一个下拉选):

这种多一个参数时,则需要修改两个地方就好了。

第一个是JSP:

如:

[html] view plain copy

print?

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%@ page isELIgnored="false" %>
  3. <%-- <%@ page language="java" contentType="text/html; charset=UTF-8" --%>
  4. <%--     pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%> --%>
  5. <!DOCTYPE HTML>
  6. <html>
  7. <head>
  8. <meta charset="UTF-8" />
  9. <title>数据生成</title>
  10. </head>
  11. <body>
  12. <div>
  13. <form method="post" id="file" action="" enctype="multipart/form-data">
  14. <select id="select">
  15. <option value="1">1</option>
  16. <option value="2">2</option>
  17. <option value="3">3</option>
  18. <option value="4">4</option>
  19. <option value="5">5</option>
  20. </select>
  21. <h3>选择一个文件:</h3>
  22. <input id="excelFile" type="file" name="uploadFile" />
  23. <br/><br/>
  24. <input type="button" value="上传" onclick="uploadFiles();"/>
  25. </form>
  26. </div>
  27. </body>
  28. <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  29. <script>
  30. function uploadFiles(){
  31. var formData = new FormData();
  32. var uploadFile = $(‘#excelFile‘).get(0).files[0];
  33. //  var uploadFile = new FormData($("#file")[0]);
  34. var selectedId = $(‘#select‘).val();
  35. formData.append("uploadFile",uploadFile);
  36. formData.append("selectedId", selectedId);
  37. console.log(uploadFile);
  38. if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
  39. $.ajax({
  40. url:‘/manage/fileupload/upload‘,
  41. type:‘POST‘,
  42. data:formData,
  43. async: false,
  44. cache: false,
  45. contentType: false, //不设置内容类型
  46. processData: false, //不处理数据
  47. success:function(data){
  48. console.log(data);
  49. alert(data.msg);
  50. },
  51. error:function(){
  52. alert("上传失败!");
  53. }
  54. })
  55. }else {
  56. alert("选择的文件无效!请重新选择");
  57. }
  58. }
  59. </script>
  60. </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page isELIgnored="false" %><%-- <%@ page language="java" contentType="text/html; charset=UTF-8" --%><%--     pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%> --%><!DOCTYPE HTML><html><head>    <meta charset="UTF-8" />    <title>数据生成</title></head><body>    <div>        <form method="post" id="file" action="" enctype="multipart/form-data">            <select id="select">                <option value="1">1</option>                <option value="2">2</option>                <option value="3">3</option>                <option value="4">4</option>                <option value="5">5</option>            </select>            <h3>选择一个文件:</h3>            <input id="excelFile" type="file" name="uploadFile" />            <br/><br/>            <input type="button" value="上传" onclick="uploadFiles();"/>        </form>    </div></body><script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script><script>function uploadFiles(){      var formData = new FormData();    var uploadFile = $(‘#excelFile‘).get(0).files[0];    //  var uploadFile = new FormData($("#file")[0]);    var selectedId = $(‘#select‘).val();    formData.append("uploadFile",uploadFile);    formData.append("selectedId", selectedId);    console.log(uploadFile);    if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){        $.ajax({            url:‘/manage/fileupload/upload‘,            type:‘POST‘,            data:formData,            async: false,              cache: false,             contentType: false, //不设置内容类型            processData: false, //不处理数据            success:function(data){                console.log(data);                alert(data.msg);            },            error:function(){                alert("上传失败!");            }        })    }else {        alert("选择的文件无效!请重新选择");    }}   </script></html>

controller代码:

[java] view plain copy

print?

  1. package com.bigaoread.platform.web.manage.fileupload;
  2. import java.io.IOException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import javax.servlet.http.HttpServletRequest;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import com.bigaoread.platform.service.fileupload.FileUploadService;
  16. @Controller
  17. @RequestMapping("/manage/fileupload")
  18. public class FileUploadController {
  19. private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
  20. @Autowired
  21. private FileUploadService fileUploadService;
  22. @RequestMapping("/uploadPage")
  23. public String uploadPage() {
  24. return "/manage/fileupload/uploadPage";
  25. }
  26. @RequestMapping(value="/upload", method=RequestMethod.POST)
  27. @ResponseBody
  28. public Map<String, Object> uploadFile(HttpServletRequest request,
  29. @RequestParam MultipartFile uploadFile) throws IOException{
  30. String selectedId = request.getParameter("selectedId");
  31. Map<String,  Object> resultMap = new HashMap<>();
  32. resultMap = fileUploadService.uploadFile(uploadFile);
  33. return resultMap;
  34. }
  35. }
package com.bigaoread.platform.web.manage.fileupload;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.bigaoread.platform.service.fileupload.FileUploadService;@[email protected]("/manage/fileupload")public class FileUploadController {    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);        @Autowired    private FileUploadService fileUploadService;        @RequestMapping("/uploadPage")    public String uploadPage() {        return "/manage/fileupload/uploadPage";    }        @RequestMapping(value="/upload", method=RequestMethod.POST)    @ResponseBody    public Map<String, Object> uploadFile(HttpServletRequest request,            @RequestParam MultipartFile uploadFile) throws IOException{        String selectedId = request.getParameter("selectedId");        Map<String,  Object> resultMap = new HashMap<>();        resultMap = fileUploadService.uploadFile(uploadFile);        return resultMap;    }}

测试效果:

结果:

原文地址:https://www.cnblogs.com/jpfss/p/8954567.html

时间: 2024-10-16 08:23:56

使用FormData进行Ajax请求上传文件到controller层的实现的相关文章

SSM框架下,使用ajax请求上传文件(doc\docx\excel\图片等)

1.准备工作 1.1.添加上传必要jar包 <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId>

django中通过文件和Ajax来上传文件

一.通过form表单来上传文件 1.在html模板中 <form action="/index/" method="post" enctype="multipart/form-data">#在form属性中写入enctype="multipart/form-data" 这样form表单才能支持数据文件的提交 {% csrf_token %} 头像<input type="file" nam

关于ajax分段上传文件实例~

本来打算写的勤快一点的,谁知道最近好忙啊,忙着应聘的事情,这里突然想提一下自己的历程 自己现在是一只大三狗,高中三年是玩过去了,上了一所省内普通的不能再普通的二本.不过在大学里还算的上勤奋,大一上在学生会搅搅水,大一下就开始在学校网络中心里面干活,网络维护是工作,编程是兴趣,基本上每天网络中心寝室两点一线,所以说还算得上勤奋.不过现在我自己算是明白,很多事情不是勤奋就好了的,方法不对,真的是事倍功半.自己之前学习东西都是瞎倒腾,看书,看视频,记笔记,写demo.看起来稀疏平常,但是自己缺点在于太

Ajax方式上传文件

用到两个对象 第一个对象:FormData 第二个对象:XMLHttpRequest 目前新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 FormData 对象,还在用IE6 ? 只能仰天长叹.... 有了这两个对象,我们可以真正的实现Ajax方式上传文件. 示例代码: <!DOCTYPE html> <html> <head> <title>Html5 Ajax 上传文件</title>

ajax jquery 上传文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ include file="/WEB-INF/jsp/commons/includes.jsp"%> <html> <head> <title>${systemName }</title> <style t

解决ajax异步上传文件的问题

HTML: <form id="avater" name="formlist"> {{ csrf_field() }} <ul class="list-group container" style="width:50%"> <li class="list-group-item list" style="border-radius: 5px"> <

jquery ajax实现上传文件代码,带进度条

原文:jquery ajax实现上传文件代码,带进度条 源代码下载地址:http://www.zuidaima.com/share/1550463291116544.htm ajax上传文件代码,带进度条的. 首页 http://localhost:端口/项目名/common/test.htm 上传中 标签: jquery ajax 上传 进度条话题: Web开发 前端技术 jquery ajax实现上传文件代码,带进度条

通过Ajax方式上传文件,使用FormData进行Ajax请求

通过传统的form表单提交的方式上传文件: 1 2 3 4 5 6 7 8 9 <form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">       <h1 >测试通过Rest接口上传文件 </h1&g

通过Ajax方式上传文件(图片),使用FormData进行Ajax请求

HTML: <form id= "uploadForm"> <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上传文件: <input type="file" name="file"/></ p> <input ty