需要的包:spring的21个包,commons-fileupload/io/logging的三个包,标准标签库2个包
异常处理:如果报BeanCreationException: Lookup method resolution failed 可能是缺少必须的包;
spring-servlet.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.hanqi.controller"></context:component-scan><!--注解扫描器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 视图解析器 -->
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置spring里带的文件上传类-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 可以上传的文件的总大小, 单位(b), 1KB=1024b -->
<property name="maxUploadSize" value="1000000000"></property>
<!-- 可以上传的单个文件的大小, 单位(b) -->
<property name="maxUploadSizePerFile" value="100000000"></property>
<!-- 默认的字符集 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</beans>
文件上传页:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<form action="file/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" ><br>
<input type="submit" value="提交">
</form><br>
<a href="${pageContext.request.contextPath }/download.do">查看上传文件</a>
</body>
</html>
文件下载页:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="index.jsp">上传文件</a><br>
<!--第一种下载方式,直接加上download属性即可,仅支持火狐和谷歌浏览器-->
<c:forEach items="${fileList}" var="f">
<a href="files/${f}" download>${f }</a><br>
</c:forEach>
<!--第二种下载方式,将文件名作为请求参数传入后台-->
<c:forEach items="${fileList}" var="f">
<a href="file/download.do?filename=${f }">${f }</a><br>
</c:forEach>
</body>
</html>
文件控制器类:
package com.hanqi.controller;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/upload")
public String upload(MultipartFile file,HttpServletRequest request) {
System.out.println(file.getName());// input控件中name属性的值
System.out.println(file.getSize()); // 文件大小
System.out.println(file.getOriginalFilename());// 文件名
//在WebContent下新建一个files文件夹,并获取其物理路径
String path = request.getServletContext().getRealPath("/files");
//新建一个空的文件,File.separator相当于"/",同时加上一个时间戳,用于区分相同名字的文件
File orgFile = new File(path + File.separator + new Date().getTime()+"-" + file.getOriginalFilename());
try {
//将接收到的文件放到空的文件中
//该文件实际存放在D:eclipse workspace.metadata.pluginsorg.eclipse.wst.server.core
// mp0wtpwebappsspring-filefiles
file.transferTo(orgFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
@RequestMapping("/download")
public ResponseEntity<byte[]> testDownLoad(
HttpServletRequest request,
String filename) throws Exception {
// String orgFilename = new String(filename.getBytes("iso-8859-1"), "utf-8");
String path =
request.getServletContext().getRealPath("/files");
// File orgFile = new File(path + "/" + orgFilename);
File orgFile = new File(path + "/" + filename);
// 设置请求头信息
HttpHeaders hh = new HttpHeaders();
// 告诉前台, 以(attachement, 就是下载)的方式打开文件
hh.setContentDispositionFormData("attachment", new String(filename.getBytes("utf-8"), "iso-8859-1"));
// 以二进制流的形式传输文件, 这是最常见的下载方式
hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(orgFile), hh,
HttpStatus.CREATED);
}
}
页面跳转控制类:
package com.hanqi.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FormController {
@RequestMapping("/{path}")
public String toPage(@PathVariable("path")String page,Model model,HttpServletRequest request) {
if("download".equals(page)) {
String path = request.getServletContext().getRealPath("/files");
File orgFiles = new File(path);
File[] files = orgFiles.listFiles();
List fileList = new ArrayList();
for(File f:files) {
fileList.add(f.getName());
}
model.addAttribute("fileList", fileList);
}
return page;
}
}