利用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

利用spring的MultipartFile实现文件上传【原】的更多相关文章

  1. Spring MVC - MultipartFile实现文件上传(单文件与多文件上传)

    准备工作: 需要先搭建一个spirngmvc的maven项目 1.加入jar包 <dependency> <groupId>commons-fileupload</gro ...

  2. spring MVC multipart处理文件上传

    在开发Web应用程序时比较常见的功能之一,就是允许用户利用multipart请求将本地文件上传到服务器,而这正是Grails的坚固基石——Spring MVC其中的一个优势.Spring通过对Serv ...

  3. Spring中MultipartHttpServletRequest实现文件上传

    Spring中MultipartHttpServletRequest实现文件上传 转贴自:http://my.oschina.net/nyniuch/blog/185266 实现图片上传  用户必须能 ...

  4. 关于我使用spring mvc框架做文件上传时遇到的问题

    非常感谢作者 原文:https://blog.csdn.net/lingirl/article/details/1714806 昨天尝试着用spring mvc框架做文件上传,犯了挺多不该犯的毛病问题 ...

  5. Spring MVC-从零开始-文件上传(未完待续)

    Spring MVC-从零开始-文件上传(未完待续)

  6. Spring MVC MultipartFile实现图片上传

    <!--Spring MVC xml 中配置 --><!-- defaultEncoding 默认编码;maxUploadSize 限制大小--><!-- 配置Multi ...

  7. Spring中MultipartHttpServletRequest实现文件上传 生成缩略图

    转贴自:http://my.oschina.net/nyniuch/blog/185266 实现图片上传  用户必须能够上传图片,因此需要文件上传的功能.比较常见的文件上传组件有Commons Fil ...

  8. spring mvc中的文件上传

    使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...

  9. SpringMVC 使用MultipartFile实现文件上传(转)

    http://blog.csdn.net/kouwoo/article/details/40507565 一.配置文件:SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们 ...

随机推荐

  1. Django+Xadmin打造在线教育系统(七)

    全局导航&个人中心&全局搜索 配置全局导航 让index页面也继承base页面,注意首页有个单独的__index.js__ base页面的导航栏也进行配置 <nav> &l ...

  2. project 2013 设置工期为1个工作日,但开始时间与结束时间不是同一天

    1.问题描述 project2013在工期栏输入  1  ,在开始时间结束时间点自动安排,就会出现如下情况,会被误认为是两天 2.问题解决 文件-->选项-->常规-->日期格式选择 ...

  3. requirements文件

    将一个环境中安装的所有的包在另一个环境中安装 1.生成文件列表 pip freeze > requirements.txt 2.将该文件放入到新环境中,安装 pip install -r req ...

  4. Linux 通过Shell 查找问题进程 [转]

    背景介绍: 最近公司服务器不太稳定,总是在凌晨某个时段突发高负载情况,因为客观环境比较复杂,所以很难猜测出到底是哪个进程出现了问题,加之故障发生时,通常我在睡觉,等我被报警短信吵醒,通过公司 VPN ...

  5. SDOI2017 Round1 简要题解

    我们 TM 怎么又要上文化课..我 哔哔哔哔哔哔 「SDOI2017」数字表格 题意 有 \(T\) 组数据,求 \[ \prod_{i = 1}^{n} \prod_{j = 1}^{m} fib[ ...

  6. HDU6341 Let Sudoku Rotate (杭电多校4J)

    给一个由4*4个4*4的小格组成数独,这些数独是由一个块逆时针旋转得来的,所以要还原的话就模拟出顺时针的过程,先把里面的字母转化成数字,然后从第一个块开始枚举,每个dfs和之前枚举的已经满足条件的块, ...

  7. 洛谷4451 整数的lqp拆分(生成函数)

    比较水的一题.居然是一道没看题解就会做的黑题…… 题目链接:洛谷 题目大意:定义一个长度为 $m$ 的正整数序列 $a$ 的价值为 $\prod f_{a_i}$.($f$ 是斐波那契数)对于每一个 ...

  8. LVS+Keepalived搭建高可用负载均衡

    应用环境: LVS负责多台WEB端的负载均衡(LB):Keepalived负责LVS的高可用(HA),这里介绍主备模型. 测试环境: 配置步骤: 1. 安装软件 在LVS-1和LVS-2两台主机上安装 ...

  9. 在 Docker 中使用 mysql 的一些技巧

    启动到后台:  docker-compose start docker-composer 执行命令: entrypoint: pwd app: build: ./app working_dir: /a ...

  10. bzoj2194 快速傅里叶之二

    题意:对于k = 0 ... n求 解: 首先把i变成从0开始 我们发现a和b的次数(下标)是成正比例的,这不可,于是反转就行了. 反转b的话,会发现次数和是n + k,这不可. 反转a就很吼了. 这 ...