【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. 自制反汇编工具使用实例 其二(使用xmm寄存器初始化对象,以及空的成员函数指针)

    在反汇编代码中,当看到xmm寄存器,第一反应是将要进行浮点操作或访问,但是更加多的情况是在使用xmm寄存器初始化局部对象. 下面是自制反汇编工具翻译出来的代码: // -[CALayer setAll ...

  2. python进程与线程的操作

    进程操作: # project :Python_Script # -*- coding = UTF-8 -*- # Autohr :XingHeYang # File :processTest.py ...

  3. react 组件间通信,父子间通信

    一.父组件传值给子组件 父组件向下传值是使用了props属性,在父组件定义的子组件上定义传给子组件的名字和值,然后在子组件通过this.props.xxx调用就可以了. 二.子组件传值给父组件 子组件 ...

  4. wordpress小程序安装教程

    推荐服务器特价优惠注册即可购买,1G双核一年只要88,真的是白菜价格,点击下面图片即可进入购买地址. 开源小程序发布一段时间了,很多人最近咨询了关于小程序的教程,实在太忙了,抽空写个基本的安装教程. ...

  5. Dart Learn Notes 04

    流程控制语句 流程控制语句的作用就是控制代码的执行流程. if and else var a = 10; if(a > 10){ print('ok'); }else if( 5 < a ...

  6. python之turtle画蚊香

    原理:利用turtle绘制圆形,并使圆半径逐步增加 代码如下: import turtle turtle.pensize(30) for i in range(30): turtle.circle(i ...

  7. 图解 Spring:HTTP 请求的处理流程与机制【4】

    4. HTTP 请求在 Spring 框架中的处理流程 在穿越了 Web 容器和 Web 应用之后,HTTP 请求将被投送到 Spring 框架,我们继续剖析后续流程.Web 应用与 Spring M ...

  8. linux防火墙的相关命令

    一.iptables防火墙(需要安装防火墙sudo apt-get install firewalld命令查看插件)1.基本操作 # 查看防火墙状态 service iptables status # ...

  9. AJAX入门介绍

    在我们平时的开发过程中,经常使用到Ajax数据交互,相信有很大一部分人会使用,可能没太详细了解过Ajax的工作原理.下面我们一起看一下吧! ( 一 ) 什么是Ajax Ajax 即“Asynchron ...

  10. synchronized被这么问,谁能受得了

    synchronized是面试中经常会被问到的知识点,相关的问题点也很多,问题答案涉及的知识点也很多,有经验的面试官就会顺着你的答案不断追问一下,下面的对话场景就是相关面试题的连环炮. 面试官:说一下 ...