【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. pandas的使用(5)

    pandas的使用(5)-- 缺失值的处理

  2. 领扣(LeetCode)错误的集合 个人题解

    集合 S 包含从1到 n 的整数.不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复. 给定一个数组 nums 代表了集合 S ...

  3. 领扣(LeetCode)二叉树的右视图 个人题解

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值. 示例: 输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 < ...

  4. expect 自动填充密码

    它的脚本以#!/usr/bin/expect开头,执行时用expoct,而不是bash.我的一个给samba自动创建用户并且自动填写默认密码的脚本如下: vim smb_passwd.exp #!/u ...

  5. vue响应式的注意事项

    在html中出现无法显示对象属性的情况,可能是需要在初始化对象时,先定义好属性. <template> <div> <div v-else class="req ...

  6. mac中安装Jenkins+jdk

    Jenkins是基于Java开发的一种持续集成工具,用于持续的软件版本发布/测试项目,并监控外部调用执行的工作.简单来说就是自动化测试+部署. 首先我们需要安装jdk,注意,目前jenkins只支持j ...

  7. [ML机器学习 - Stanford University] - Week1 - 01 Introduction

    What is Machine Learning? Two definitions of Machine Learning are offered. Arthur Samuel described i ...

  8. PowerMock学习(五)之Verifying的使用

    前言 Verifying是一个非常强大的测试工具,在mock系列框架中使用广泛,主要用于验证方法是否被调用,下面将举例说明. 场景 模拟这样一个场景,通过Dao查询学生,如果存在更新原来学生,不存在则 ...

  9. Linux\Nginx 虚拟域名配置及测试验证

    使用 Nginx 虚拟域名配置,可以不用去购买域名,就可以通过特定的域名访问本地服务器.减少发布前不必要的开支. 配置步骤 1. 编辑 nginx.conf 配置文件 sudo vim /usr/lo ...

  10. MySQL数据库优化技巧有哪些?

    开启查询缓存,优化查询. explain你的select查询,这可以帮你分析你的查询语句或是表结构的性能瓶颈.EXPLAIN的查询结果还会告诉你你的索引主键被如何利用的,你的数据表是如何被搜索和排序的 ...