【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. ArcGIS API For Javascript :如何在地图上做出点位脉冲闪烁的效果

    日常地图表达中我们通常使用的地图符号多是静态地图符号,时间久了会造成视觉审美疲劳,也没有现代感. 在这种背景下,对现有地图符号进行简单处理,即可得到色彩鲜艳,对比度强烈,活灵活现的地图表达形式. 灵感 ...

  2. bash:echo

    echo 'xxxx'自带换行 echo -n ‘xxxxxx’ 取消换行 echo -e "xxxxxxxxxxxx"允许转义字符(两种引号对转以字符效果相同,影响$变量) 转义 ...

  3. 通过django 速成 blog

    1.            创建项目 33进入在python目录下的scripts文件后执行 django-admin.py   startproject  mysite 这样就生成了名为mysite ...

  4. Mac 下安装并配置 Tomcat

    1,下载 点击 官网 ,进入下载页面, 2,安装 解压出来,即安装完成. 移动解压后的文件,换个文件目录(方便集中管理),将它改个名字(毕竟名字太长了). 我将其改名为 tomcat9 ,移入资源库目 ...

  5. 揭秘String类型背后的故事——带你领略汇编语言魅力

    字符串或串(String)是由数字.字母.下划线组成的一串字符.一般记为 s=“a1a2···an”(n>=0).它是编程语言中表示文本的数据类型.在程序设计中,字符串(string)为符号或数 ...

  6. Java 浅拷贝、深拷贝,你知多少?

    这是今天我们在技术群里面讨论的一个知识点,讨论的相当激烈,由于对这一块使用的比较少,所以对这一块多少有些盲区.这篇文章总结了所讨论的内容,希望这篇文章对你有所帮助. 在 Java 开发中,对象拷贝或者 ...

  7. shell中的函数、shell中的数组、告警系统需求分析

    7月16日任务 20.16/20.17 shell中的函数20.18 shell中的数组20.19 告警系统需求分析 20.16/20.17 shell中的函数 函数就是一个子shell就是一个代码段 ...

  8. 使用echarts常用问题总结

    1,echarts配合element ui的抽屉插件出现报错,上次解决方法是使用element ui 抽屉的open事件,让在打开事件重新加载,我们项目的需求是点击某个数据,要传递这条数据包含的其他值 ...

  9. 谈一谈个人利用Java的mysql的知识完成的数据库的项目-----用户信息管理系统

    首先,我先简述一下自己做的过程啊,相信大家来找这样的博客,也都是为了完成自己课程任务吧.我也一样是一名大一的学生,是为了自己的课程任务而开始做数据库的项目的.因为还没学mysql吗,所以是自己找视频啊 ...

  10. 面试一个小公司,TPM相关概念

    准备面试一个小公司,在面试邀请邮件中提出了这样一个要求(not required): ".. one item we will likely discuss with you is soft ...