1. 准备jar包 : commons-fileupload-1.3.2.jar
commons-io-2.2.jar
2.
spring-mvc.xml 添加
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000"/>
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960"/>
<!-- 上传文件的临时路径 -->
<property name="uploadTempDir" value="fileUpload/temp"/>
</bean>
3.controller.java
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception{
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("//")+"/upload/"
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
System.out.println("**********"+filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
return "success";
}
4.upload.jsp
<%@ 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>Insert title here</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap-theme.min.css">
<script src="${pageContext.request.contextPath}/js/jquery-1.11.2.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</head>
<body style="padding: 20px">
<form action="${pageContext.request.contextPath}/user/upload.do" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>
下载:
controller.java
@RequestMapping("download")
public ResponseEntity<byte[]> download(String path) throws IOException {
File file=new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName=path.substring(path.lastIndexOf("/")+1);
fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
download.jsp
<a class="tooltip-test" data-toggle="tooltip" title="下载文件" href="download.do?path=${wfDeployment.path }">