【Java Web开发学习】Spring MVC文件上传

转载:https://www.cnblogs.com/yangchongxing/p/9290489.html

文件上传有两种实现方式,都比较简单

方式一、使用StandardServletMultipartResolver

依赖Servlet3.0对Multipart请求的支持,需要MultipartConfigElement配置请求的相关参数

Java配置方式

@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}

在Servlet中指定multipart配置,通过MultipartConfigElement设置上传临时路径,上传文件大小,上传请求的大小。

通过重载protected void customizeRegistration(ServletRegistration.Dynamic registration)方法实现,看代码

package cn.ycx.web.config;

import java.io.IOException;
import java.util.Properties; import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { // 将一个或多个路径映射到DispatcherServlet上
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
} // 返回的带有@Configuration注解的类将会用来配置ContextLoaderListener创建的应用上下文中的bean
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {ServletConfig.class};
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// 上传文件的临时目录
String location = "/tmp";
// 上传文件的最大容量
long maxFileSize = 3145728;
// 请求的最大容量
long maxRequestSize = 3145728;
// 上传的最小临界值,大于该值才会被写入文件保存
// int fileSizeThreshold = 0;
try {
Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("upload.properties"));
location = prop.getProperty("temporary.location");
maxFileSize = Long.parseLong(prop.getProperty("max.file.size"));
maxRequestSize = Long.parseLong(prop.getProperty("max.request.size"));
} catch (IOException e) {}
// 文件上传配置
registration.setMultipartConfig(new MultipartConfigElement(location, maxFileSize, maxRequestSize, 0));
// 没有找到处理的请求抛出异常
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
if(!done) throw new RuntimeException("设置异常(throwExceptionIfNoHandlerFound)");
}
}

xml-base方式

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

web.xml配置DispatcherServlet初始化参数

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
...省略...
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
<multipart-config>
<!--临时文件的目录-->
<location>E:/tmp</location>
<!-- 上传文件最大3M -->
<max-file-size>3145728</max-file-size>
<!-- 上传文件整个请求不超过3M -->
<max-request-size>3145728</max-request-size>
</multipart-config>
</servlet>
...省略...
</web-app>

Html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/mvc/upload" enctype="multipart/form-data" method="post">
<input name="fileData" type="file">
<input type="submit" value="上传">
</form>
</body>
</html>

1、控制器接受文件原始byte[]。这种方式不可取,虽然能保存文件,但是我们不知道文件原始名称,也不知道文件类型。

    @RequestMapping("/upload")
public Map<String, String> upload(@RequestPart("fileData") byte[] fileData) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHssmm");
if (fileData != null) {
FileOutputStream out = new FileOutputStream(new File("F:\\war\\" + format.format(new Date())));
out.write(fileData);
out.close();
}
Map<String, String> data = new HashMap<String, String>();
data.put("status", "ok");
return data;
}

 2、控制器接受MultipartFile类型

Multipart接口

public interface MultipartFile extends InputStreamSource {
String getName();//参数名字
String getOriginalFilename();//原始文件名
String getContentType();//类型
boolean isEmpty();//文件是否空
long getSize();//文件字节大小
byte[] getBytes() throws IOException;//返回字节数组
@Override
InputStream getInputStream() throws IOException;//输入流
void transferTo(File dest) throws IOException, IllegalStateException;//转换文件
}

控制器代码

    @RequestMapping("/upload")
public Map<String, String> upload(MultipartFile fileData) throws Exception {
if (fileData != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHssmm");
fileData.transferTo(new File("F:\\war\\" + format.format(new Date()) + "_" + fileData.getOriginalFilename()));//保存文件
}
Map<String, String> data = new HashMap<String, String>();
data.put("status", "ok");
return data;
}

3、控制器接受Part类型

Part接口

public interface Part {
public InputStream getInputStream() throws IOException;//输入流
public String getContentType();//类型
public String getName();//参数名
public String getSubmittedFileName();//原始文件名
public long getSize();//字节大小
public void write(String fileName) throws IOException;//保存文件
public void delete() throws IOException;//删除文件
public String getHeader(String name);//获取头信息
public Collection<String> getHeaders(String name);//获取头信息
public Collection<String> getHeaderNames();//获取头信息
}

控制器代码

    @RequestMapping("/upload")
public Map<String, String> upload(@RequestPart("fileData") Part fileData) throws Exception {
if (fileData != null) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHssmm");
fileData.write("F:\\war\\" + format.format(new Date()) + "_" + fileData.getSubmittedFileName());//保存文件
}
Map<String, String> data = new HashMap<String, String>();
data.put("status", "ok");
return data;
}

方式二、使用CommonsMultipartResolver

依赖 commons-fileupload.jar 和 commons-io.jar。上传临时路径,文件大小都在对象中设置。

code-base方式

@Bean
public MultipartResolver multipartResolver() throws IOException {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setUploadTempDir(new FileSystemResource(config.uploadTemporaryLocation()));
multipartResolver.setMaxUploadSize(config.uploadMaxFileSize());
multipartResolver.setMaxInMemorySize(0);
return multipartResolver;
}

xml-base方式

<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>

示例代码:

实现了核心部分仅供参考。

package cn.ycx.web.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date; 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 cn.ycx.web.config.PropertyConfig; /**
* 上传
* @author 杨崇兴 2018-07-09
*/
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
/**
* 属性配置
*/
@Autowired
private PropertyConfig config; @RequestMapping(value="/image", method=RequestMethod.POST, produces="application/json;charset=UTF-8")
public String image(@RequestParam(value = "imageFile", required = false) MultipartFile multipartFile) {
try {
String serverPath = config.uploadImageSavePath() + new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
File serverPathFile = new File(serverPath);
//目录不存在则创建
if (!serverPathFile.exists()) {
serverPathFile.mkdirs();
}
String fileName = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File(serverPath + fileName));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传</title>
</head>
<body>
<form action="/ycxcode/upload/image" method="post" enctype="multipart/form-data">
<input type="text" name="discription" value="discription"/>
<input type="file" name="imageFile">
<input type="submit" value="submit"/>
</form>
</body>
</html>

【Java Web开发学习】Spring MVC文件上传的更多相关文章

  1. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  2. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  3. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  4. Spring mvc 文件上传到文件夹(转载+心得)

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  5. Spring MVC 文件上传

    1.form的enctype=”multipart/form-data” 这个是上传文件必须的 2.applicationContext.xml中 <bean id=”multipartReso ...

  6. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

  7. spring MVC 文件上传错误

    1.The request sent by the client was syntactically incorrect () http://luanxiyuan.iteye.com/blog/187 ...

  8. Spring MVC文件上传处理

    以下示例显示如何在使用Spring Web MVC框架的表单中上传文件和处理.首先使用Eclipse IDE来创建一个WEB工程,实现一个上传文件并保存的功能.并按照以下步骤使用Spring Web ...

  9. Strut2 和Spring MVC 文件上传对比

    在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/proper/commo ...

随机推荐

  1. 【Java】面向对象之多态

    生活中,比如动物中跑的动作,小猫.小狗和大象,跑起来是不一样的.再比如飞的动作,昆虫.鸟类和飞机,飞起来也是不一样的.可见,同一类的事物通过不同的实际对象可以体现出来的不同的形态.多态,描述的就是这样 ...

  2. 业务领域建模Domain Modeling

    我的工程实践选题为ESP32低功耗的实现,本项目基于ESP32嵌入式开发平台.下文将以需求为基础,对该项目进行领域建模. 一.概念介绍 1.业务建模 1.1 概念介绍 业务建模(Business Mo ...

  3. Centos下的MySQL安装及配置

    里使用的是VMware虚拟机和Centos7系统 虚拟机安装这里不多讲,网上教程很多了,这里就介绍下虚拟机的网络配置. 虚拟机网络配置 Centos网络连接模式这里设置为桥接模式,不用勾选复制物理网络 ...

  4. 区块链共识机制之工作量证明(POW)

    像比特币.以太坊.NXT.Bitshares等这些区块链系统,其本质上是一种加密经济组织,它建立在点对点网络上,是去中心化.无管辖的,由密码学.经济学和社会共识来共同维护.这些加密网络因各种原因有着多 ...

  5. ubuntu server 1604 关机和重启

    命令有很多,记住以下两三个就够了 重启: sudo reboot (这个短,易记) sudo shutdown -r now  统一的shutdown形式 关机:sudo shutdown -P no ...

  6. HBase 基本入门

    目录 一.简介 有什么特性 与RDBMS的区别 二.数据模型 三.安装HBase 四.基本使用 表操作 五.FAQ 参考文档 无论是 NoSQL,还是大数据领域,HBase 都是非常"炙热& ...

  7. 【RocketMQ源码学习】- 5. 消息存储机制

    前言 面试官:你了解RocketMQ是如何存储消息的吗?我:额,,,你等下,我看下这篇文字, (逃 由于这部分内容优点多,所以请哥哥姐姐们自备茶水,欢迎留言! RocketMQ存储设计是高可用和高性能 ...

  8. JVM(2)--深入理解java对象创建始终

    java对象探秘 java是一门面向对象的语言,我们无时无刻不在创建对象和使用对象,那么java虚拟机是如何创建对象的?又是如何访问对象的?java对象中究竟存储了什么运行时所必需的数据?在学习了ja ...

  9. 【Android - 自定义View】之不同事件的处理

    在Android的自定义View中,往往需要处理一系列的事件,如触摸事件.双击事件.缩放事件等.本文将这些事件及其处理进行总结.本文将持续更新,将我在自定义View的实践中用到的事件及其处理进行总结. ...

  10. 【BZOJ2190】【Luogu P2158】 [SDOI2008]仪仗队

    前言: 更不好的阅读 这篇题解真的写了很久,改了又改才成为这样的,我不会写题解但我正在努力去学,求通过,求赞... 题目: BZOJ Luogu 思路: 像我这样的数论菜鸡就不能一秒切这题,怎么办呢? ...