文章目录
1 文件上传概述1.1 代码实现
2 文件下载2.1 中文名文件下载2.2 代码实现
1 文件上传概述
多数文件都是通过表单形式提交给后台服务器的,实现文件上传功能就需要一个表单,需要满足如下三个条件:
form表单的method属性设置为postform表单的enctype属性设置为multipart/form-data提供<input type="file" name="filename">的文件上传输入框
当form表单的enctype属性为multipart/form-data时,浏览器就会采用二进制流来处理表单数据,服务器端就会对文件上传的请求进行解析处理,Spring MVC通过MultipartResolver实现文件上传功能。这是一个接口对象,需要通过它的实现类CommonsMultipartResolver来完成文件上传功能。在springmvc-config.xml中配置如下:
注意:因为MultipartResolver接口的实现类CommonsMultipartResolver内部是引用multipartResolver字符串获取该实现类对象并完成文件解析的,所以在配置CommonsMultipartResolver时必须指定该Bean的id为multipartResolver。
MultipartResolver可以配置的属性有:
由于CommonsMultipartResolver是Spring MVC内部通过ApacheCommons FileUpload技术实现的,所以Spirng MVC的文件上传还需要依赖ApacheCommons FileUpload的组件,即需要导入支持文件上传的相关JAR包。
commons-fileupload-1.3.2.jarcommons-io-2.5.jar
1.1 代码实现
pom.xml添加依赖
<dependency>
<groupId>commons-fileupload
</groupId>
<artifactId>commons-fileupload
</artifactId>
<version>1.4
</version>
</dependency>
springmvc-config.xml中配置MultipartResolver
<bean id
="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置请求编码格式
-->
<property name
="defaultEncoding" value
="UTF-8" />
</bean
>
FileUploadController.java
package cn
.edu
.ujn
.ch16
.controller
;
import java
.io
.File
;
import java
.util
.List
;
import java
.util
.UUID
;
import javax
.servlet
.http
.HttpServletRequest
;
import org
.springframework
.stereotype
.Controller
;
import org
.springframework
.web
.bind
.annotation
.RequestMapping
;
import org
.springframework
.web
.bind
.annotation
.RequestParam
;
import org
.springframework
.web
.multipart
.MultipartFile
;
@Controller
public class FileUploadController {
@RequestMapping("/fileUpload")
public String
handleFormUpload(@RequestParam("name") String name
,
@RequestParam("uploadfile") List
<MultipartFile> uploadfile
, HttpServletRequest request
) {
if (!uploadfile
.isEmpty() && uploadfile
.size() > 0) {
for (MultipartFile file
: uploadfile
) {
String originalFilename
= file
.getOriginalFilename();
String dirPath
= request
.getServletContext().getRealPath("/upload/");
File filePath
= new File(dirPath
);
if (!filePath
.exists()) {
filePath
.mkdirs();
}
String newFilename
= name
+ "_" + UUID
.randomUUID() + "_" + originalFilename
;
try {
file
.transferTo(new File(dirPath
+ newFilename
));
} catch (Exception e
) {
e
.printStackTrace();
return "error";
}
}
return "success";
} else {
return "error";
}
}
}
fileUpload.jsp
<%@ page language
="java" contentType
="text/html; charset=UTF-8"
pageEncoding
="UTF-8"%>
<%@ page isELIgnored
="false" %>
<!DOCTYPE html
>
<html>
<head>
<meta http
-equiv
="Content-Type" content
="text/html; charset=UTF-8">
<title>文件上传
</title
>
<script>
function
check(){
var name
= document
.getElementById("name").value
;
var file
= document
.getElementById("file").value
;
if(name
==""){
alert("填写上传人");
return false;
}
if(file
.length
==0||file
==""){
alert("请选择上传文件");
return false;
}
return true;
}
</script
>
</head
>
<body>
<form action
="${pageContext.request.contextPath }/fileUpload"
method
="post" enctype
="multipart/form-data" onsubmit
="return check()">
上传人:
<input id
="name" type
="text" name
="name" /><br
/>
请选择文件:
<input id
="file" type
="file" name
="uploadfile"
multiple
="multiple" /><br
/>
<input type
="submit" value
="上传" />
</form
>
</body
>
</html
>
2 文件下载
文件下载就是将文件服务器中的文件下载到本机,在Spring MVC环境中,实现文件下载分为两个步骤:
在客户端页面使用一个文件下载的超链接,该链接的herf属性要指定后台文件下载的方法及文件名(需要现在文件下载目录中添加一个名为“1.jpg”的文件)
2. 在后台使用Spring MVC提供的ResponseEntity类型对象完成文件下载,使用它可以很方便的定义返回的HttpHeaders对象和HttpStatus对象,通过这两个对象的设置,即完成下载文件时所需的配置信息。
2.1 中文名文件下载
在下载页面中对中文文件名编码,可以收用Servlet API中URLEncoder.encoder(String s,String enc)方法将中文转为UTF-8编码 download.jsp如下:
<%@ page language
="java" contentType
="text/html; charset=UTF-8"
pageEncoding
="UTF-8"%>
<%@page import="java.net.URLEncoder"%>
<%@ page isELIgnored
="false" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http
-equiv
="Content-Type" content
="text/html; charset=UTF-8">
<title>下载页面
</title
>
</head
>
<body>
<%-- <a href
="${pageContext.request.contextPath }/download?filename=1.jpg">
文件下载
</a
> --%>
<a href
="${pageContext.request.contextPath }/download?filename=<%=URLEncoder.encode("壁纸
.jpg
", "UTF
-8")%>">
中文名称文件下载
</a
>
</body
>
</html
>
在控制器类中编写对中文名文件下载时进行转码编码的方法:
public String
getFilename(HttpServletRequest request
, String filename
) throws Exception
{
String
[] IEBrowserKeyWords
= { "MSIE", "Trident", "Edge" };
String userAgent
= request
.getHeader("User-Agent");
for (String keyWord
: IEBrowserKeyWords
) {
if (userAgent
.contains(keyWord
)) {
return URLEncoder
.encode(filename
, "UTF-8");
}
}
return new String(filename
.getBytes("UTF-8"), "ISO-8859-1");
}
2.2 代码实现
配置文件同文件上传,在控制器类中添加如下方法:
@RequestMapping("/download")
public ResponseEntity
<byte[]> fileDownload(HttpServletRequest request
, String filename
) throws Exception
{
String path
= request
.getServletContext().getRealPath("/upload/");
File file
= new File(path
+ File
.separator
+ filename
);
filename
= this.getFilename(request
, filename
);
HttpHeaders headers
= new HttpHeaders();
headers
.setContentDispositionFormData("attachment", filename
);
headers
.setContentType(MediaType
.APPLICATION_OCTET_STREAM
);
return new ResponseEntity<byte[]>(FileUtils
.readFileToByteArray(file
), headers
, HttpStatus
.OK
);
}
public String
getFilename(HttpServletRequest request
, String filename
) throws Exception
{
String
[] IEBrowserKeyWords
= { "MSIE", "Trident", "Edge" };
String userAgent
= request
.getHeader("User-Agent");
for (String keyWord
: IEBrowserKeyWords
) {
if (userAgent
.contains(keyWord
)) {
return URLEncoder
.encode(filename
, "UTF-8");
}
}
return new String(filename
.getBytes("UTF-8"), "ISO-8859-1");
}
声明: 若本人发布的作品涉及版权获存在其他问题,请联系我删除。 谢谢浏览!