一、配置环境
- 首先需要配置springmvc环境,文章指路:第一个SpringMVC程序
- 导入jar包:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
二、文件上传
- 文件上传配置:在springmvc配置文件中
defaultEncoding
属性要与jsp的pageEncoding属性一致(默认为ISO-8859-1)
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
- 一个简单的form表单页面
表单的 enctype 属性指定的是表单数据的编码方式,该属性有以下 3 个值:
- application/x-www-form-urlencoded:这是默认的编码方式,它只处理表单域里的 value 属性值。
- multipart/form-data:该编码方式以二进制流的方式来处理表单数据,并将文件域指定文件的内容封装到请求参数里。
- text/plain:该编码方式只有当表单的 action 属性为“mailto:”URL 的形式时才使用,主要适用于直接通过表单发送邮件的方式。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadFile2" enctype="multipart/form-data" method="post">
<input type="file" name="upFile"/>
<input type="submit" name="upload"/>
</form>
</body>
</html>
- controller类
@RequestParam("upFile")
将name=upFile控件得到的文件封装成CommonsMultipartFile 对象
public class UploadFileController {
//方法一:
@RequestMapping("/uploadFile")
public String fileUpload(@RequestParam("upFile") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
//文件输入流
InputStream is = file.getInputStream();
//文件输出流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
//方法二:
@RequestMapping("/uploadFile2")
public String fileUpload2(@RequestParam("upFile") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
String uploadFileName = file.getOriginalFilename();
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件名 : "+uploadFileName);
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
//跳转到文件上传页面
@RequestMapping("/toUpload")
public String toUploadFile(){
return "test";
}
}
- 开启tomcat测试
- 小结
上述为单文件上传,如果想要多文件上传只需要将CommonsMultipartFile
规定为数组即可
三、文件下载
- controller类
- 利用程序实现下载需要设置两个报头:
1)Web 服务器需要告诉浏览器其所输出内容的类型不是普通文本文件或 HTML 文件,而是一个要保存到本地的下载文件,这需要设置 Content-Type 的值为 application/x-msdownload。
2)Web 服务器希望浏览器不直接处理相应的实体内容,而是由用户选择将相应的实体内容保存到一个文件中,这需要设置 Content-Disposition 报头。
3)该报头指定了接收程序处理数据内容的方式,在 HTTP 应用中只有 attachment 是标准方式,attachment 表示要求用户干预。在 attachment 后面还可以指定 filename 参数,该参数是服务器建议浏览器将实体内容保存到文件中的文件名称
4)示例:
response.setHeader("Content-Type", "application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+filename);
我们这里是一张图片,不需要设置第一个报头
- DownloadFile.java
@Controller
public class DownloadFile {
@RequestMapping("/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
//要下载的文件位置
String path = request.getServletContext().getRealPath("/upload");
String fileName = "1.png";
//设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置报头
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//读取文件--输入流
InputStream input=new FileInputStream(file);
//写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
}
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/toUpload">文件上传</a>
<a href="${pageContext.request.contextPath}/download">文件下载</a>
</body>
</html>
点击文件下载就会下载load目录下文件1.png