利用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. Xadmin 组件基础使用以及全局配置

    xadmin 的安装 方式一 pip 安装 会因为编码问题导致报错 因此需要下载 更改 README.rst 后本地安装 详情点击这里 方式二 源码方式安装 在 github 上下载源码后 将 xad ...

  2. mysql 0x80004005 unable to connect to any of the specified mysql hosts

    语言:c# 问题:偶尔会出现连不上mysql 报标题的这个错误. 解决方法:把server = localhost 改为 =127.0.0.1 或者静态IP  ,按着改暂时没出现了,继续观望!

  3. zabbix 自定义 nginx 监控模板

    打开zabbix首页→配置→模板→创建模板模板名称:Template App NGINXagent 需添加自定义监控项:UserParameter=nginx.status[*],/bin/bash ...

  4. 【bzoj3456】城市规划(多项式求逆+dp)

    Description 求\(~n~\)个点组成的有标号无向连通图的个数.\(~1 \leq n \leq 13 \times 10 ^ 4~\). Solution 这道题的弱化版是poj1737, ...

  5. Leetcode 350.两个数组的交集|| By Python

    给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: nums1 = [4,9,5 ...

  6. 【BZOJ3601】一个人的数论(数论)

    [BZOJ3601]一个人的数论(数论) 题面 BZOJ 怎么这图片这么大啊... 题解 要求的是\(\displaystyle \sum_{i=1}^n [gcd(i,n)=1]i^d\) 然后把\ ...

  7. Centos 7下下载和安装docker

    sudo yum install -y device-mapper sudo modprobe dm_mod ls -l /sys/class/misc/device-mapper sudo rpm ...

  8. 【转】MySQL常见错误代码及代码说明参考

    Mariadb文档:https://mariadb.com/kb/zh-cn/mariadb/ MySQL文档:https://dev.mysql.com/doc/refman/8.0/en/ 100 ...

  9. jenkins自动打包部署项目

    首先去jenkins的官网下载安装包 https://jenkins.io/   个人下载是长期稳定的那个版本,下载后,得到一个.msi的安装包: 点击进行安装,然后一直点击下一步. jenkins会 ...

  10. pytest 1.简单介绍一,安装和如何运行

    一.pytest是一个接口测试框架,试用版起来比较轻便灵活.首先来介绍他的安装: 直接使用命令 : pip install -U pytest 通过命令 :pytest --version  来查看版 ...