利用spring的MultipartFile实现文件上传

主要依赖jar包

spring-web-3.0.6.RELEASE.jar 用到 (org.springframework.web.multipart.MultipartFile)
commons-fileupload-1.3.1.jar
commons-logging-1.0.4.jar

前台

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>上传</title> <style type="text/css">
</style> </head>
<body> <form enctype="multipart/form-data" action="/kingtool/file/upload.do" method="POST">
file:
<input id="file" type="file" name="file" />
<input type="submit" value="提交" />
</form> </body>
</html>

后台

package com.bobo.code.web.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.multipart.MultipartFile; @Controller
@RequestMapping({ "file/*" })
public class LoginController { /**
* 承保文件上传
*
* @param session
*/
@RequestMapping(value = "upload.do", method = { RequestMethod.POST, RequestMethod.GET })
public void fileUpload(HttpSession session, ModelMap modelMap, HttpServletResponse response, HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception, IOException {
String ret = "";
request.setCharacterEncoding("UTF-8");// 编码格式处理
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("fileName:------------------------------------------------------" + fileName);
// 获取文件大小kb
BigDecimal fileSize = new BigDecimal(file.getSize()).divide(new BigDecimal(1024), 2, BigDecimal.ROUND_HALF_UP);
String startFileName = fileName.substring(0, fileName.indexOf("."));
String endFileName = fileName.substring(fileName.lastIndexOf("."));
// 新文件名称
String newFileName = startFileName + "_" + Math.random() + endFileName;
// 文件保存路径
String parentPath = request.getSession().getServletContext().getRealPath("/") + "upload/";
String filePath = parentPath + newFileName;
System.out.println("filePath:-----------------------------------------------------------" + filePath);
System.out.println("System.setProperty('sun.jnu.encoding') --------" + System.getProperty("sun.jnu.encoding"));
System.setProperty("sun.jnu.encoding", "utf-8");
System.out.println("System.setProperty('sun.jnu.encoding') --------" + System.getProperty("sun.jnu.encoding"));
File newFile = new File(parentPath);
if (!newFile.exists()) {// 判断文件夹是否创建,没有创建则创建新文件夹
newFile.mkdirs();
}
boolean uploadFile = true;
// 比较上传文件大小是否超过10M
if (fileSize.compareTo(new BigDecimal(1024 * 10)) > 0) {
uploadFile = false;
ret = "上传文件的大小不能超过10Mb,请重新选择!";
}
if (uploadFile) {
try {
file.transferTo(new File(filePath));// 转存文件
ret = "上传成功!";
} catch (Exception e) {
ret = "上传失败!";
}
}
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(ret);
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
} }

spring bean配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- maxUploadSize:文件上传的最大值以byte为单位 -->
<property name="maxUploadSize" value="1024000"></property>
<property name="defaultEncoding" value="GBK"></property>
</bean>

如果不配置,可能报如下错org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present

遇见异常

异常 Required request part 'file' is not present

我遇到的问题和网上的完全不一样, 在springboot中为了能对所有获取到的request提前打印请求报文,在filter又做了一层request wraper包装处理 , 导致file 参数丢失了.

@Component
@WebFilter(filterName = "httpServletRequestFilter", urlPatterns = {
"/controller/**",
"/j_spring_security_check**"})
@Order(-)
public class HttpServletRequestFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HttpServletRequestFilter.class); @Override
public void init(FilterConfig filterConfig) throws ServletException {
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
BufferedServletRequestWrapper requestWrapper = null;
if (servletRequest instanceof HttpServletRequest) {
requestWrapper = new BufferedServletRequestWrapper((HttpServletRequest) servletRequest);
HttpSession session = requestWrapper.getSession();
try {
logger.info("----------------------------------------------------------------------");
logger.info("HttpServletRequestFilter");
logger.info("url: " + requestWrapper.getRequestURL() + "?" + requestWrapper.getQueryString());
logger.info("sessionId: " + session.getId());
logger.info("servletPath: " + requestWrapper.getServletPath());
logger.info("requestMethod: " + requestWrapper.getMethod());
logger.info("requestHeader: " + HttpServletRequestFilter.getStringFromHead((HttpServletRequest) servletRequest));
logger.info("body: " + HttpServletRequestFilter.getStringFromStream(requestWrapper));
logger.info("----------------------------------------------------------------------\n\n");
} catch (Exception e) {
e.printStackTrace();
}
filterChain.doFilter(requestWrapper, servletResponse);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}

ajax文件上传

如果用ajax文件上传时注意contentType:false 一定要为false, 不要自传多情传什么 contentType: "multipart/form-data;charset=utf-8;boundary=" + Math.random(),

不然springboot的后台controller死活不成功, 永远报错为: MissingServletRequestPartException: Required request part 'file' is not present 

<script type="text/javascript">
function upload() {
$("#result").html("upload");
var formData = new FormData();
formData.append("file", $("#file")[0].files[0]);
$.ajax({
url: 'http://localhost/controller/finance/asset/manager/upload',
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function (res) {
$("#result").html(res);
}
});
}
</script>

本小节参考: 解决springboot MultipartFile文件上传遇到的问题==>http://www.manongjc.com/article/4682.html

参考

MultipartFile+ajax图片上传==>https://blog.csdn.net/q394503873/article/details/80737323