使用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="上传" οnclick="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可参考此链接:

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="上传" οnclick="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;
	}

}

测试效果:


结果:







  • 12
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值