使用FormData进行Ajax请求上传文件到controller层的实现
Posted jpfss
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用FormData进行Ajax请求上传文件到controller层的实现相关的知识,希望对你有一定的参考价值。
需求背景:
页面上传一个文件到controller层,然后后台对文件进行处理。文件类型不限。
第一种:单纯的上传文件
页面功能展现:
第一步:首先需要两个jar
commons-fileupload-1.3.2.jar
commons-io-2.4.jar
版本不限:
pom文件中相应两个jar:
- <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中配置
- <!-- 文件上传配置 -->
- <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页面代码
- <%@ 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>
- https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
第四步:controller层代码
- 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;
- @Controller
- @RequestMapping("/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:
如:
- <%@ 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代码:
- 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;
- @Controller
- @RequestMapping("/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;
- }
- }
测试效果:
结果:
以上是关于使用FormData进行Ajax请求上传文件到controller层的实现的主要内容,如果未能解决你的问题,请参考以下文章
通过Ajax方式上传文件,使用FormData进行Ajax请求
通过Ajax方式上传文件,使用FormData进行Ajax请求
通过Ajax方式上传文件,使用FormData进行Ajax请求
H5 通过Ajax方式上传文件,使用FormData进行Ajax请求