把以前的笔记做到这里方便复制。
一、 添加依赖和配置
添加依赖pom.xml
<!-- commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
springmvc-servlet.xml中添加CommonsMultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
二、 springmvc的文件上传
在webapp目录下新建个upload文件夹。
写springmvc文件上传FileUploadController
package com.imddy.tsession.controller;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/fileupload/")
public class FileUploadController {
private static Log log = LogFactory.getLog(FileUploadController.class);
@RequestMapping("upload1")
public String upload1(HttpServletRequest request, @RequestParam("file1") MultipartFile file1) {
// 判断文件是否为空
if (!file1.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file1.getOriginalFilename();
// 转存文件
file1.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("UserName:" + username);
System.out.println("Password:" + password);
log.info("UserName:" + username);
log.info("Password:" + password);
// 重定向
return "redirect:/fileupload/filelist.do";
}
@RequestMapping("filelist")
public ModelAndView filelist(HttpServletRequest request) {
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
ModelAndView mav = new ModelAndView("/filelist");
File uploadDest = new File(filePath);
String[] fileNames = uploadDest.list();
for (int i = 0; i < fileNames.length; i++) {
//打印出文件名
System.out.println(fileNames[i]);
System.out.println(filePath);
log.info(fileNames[i]);
log.info(filePath);
}
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
mav.addObject("uploadPath", basePath+"upload/");
mav.addObject("fileNames", fileNames);
return mav;
}
@SuppressWarnings("unused")
private boolean saveFile(MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
// String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename();
String filePath = "/usr/local/upload/" + file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
private boolean saveFile2(HttpServletRequest request,MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
@RequestMapping("upload2")
public String upload2(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
//判断file数组不能为空并且长度大于0
if(files!=null&&files.length>0){
//循环获取file数组中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
System.out.println("True&False : " + saveFile2(request,file));
}
}
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("2UserName:" + username);
System.out.println("2Password:" + password);
log.info("2UserName:" + username);
log.info("2Password:" + password);
// 重定向
return "redirect:/fileupload/filelist.do";
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsp</title>
<body>
<h2>Hello World!</h2>
<a href = "t.do">t.do</a><br>
<a href = "loginGet.do">loginGet.do</a><br>
<hr>
<a href = "Test/t.do">Test/t.do</a><br>
<a href = "Test/loginGet.do">Test/loginGet.do</a><br>
<hr>
<a href = "fileupload/filelist.do">fileupload/filelist.do</a><br>
<a href = "fileupload1.jsp">fileupload1.jsp</a><br>
<a href = "fileupload2.jsp">fileupload2.jsp</a><br>
<hr>
<a href = "fileupload11.jsp">fileupload11.jsp</a><br>
<a href = "fileupload12.jsp">fileupload12.jsp</a><br>
<a href = "filedownload.jsp">filedownload.jsp</a><br>
</body>
</html>
fileupload1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
<title>fileupload.jsp</title>
</head>
<body>
<form role="form" action="fileupload/upload1.do" enctype="multipart/form-data" method="post" class="col-md-6 col-md-offset-3">
<input type="file" name="file1" placeholder="文件1">
<input type="text" name="username" class="form-control" placeholder="请输入用户名" >
<input type="password" name="password" class="form-control" placeholder="请输入密码" >
<button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
</form>
</body>
</html>
fileupload2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
<title>fileupload.jsp</title>
</head>
<body>
<form role="form" action="fileupload/upload2.do" enctype="multipart/form-data" method="post" class="col-md-6 col-md-offset-3">
<input type="file" name="files" placeholder="文件1">
<input type="file" name="files" placeholder="文件2">
<input type="file" name="files" placeholder="文件3">
<input type="text" name="username" class="form-control" placeholder="请输入用户名" >
<input type="password" name="password" class="form-control" placeholder="请输入密码" >
<button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
</form>
</body>
</html>
filelist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
<title>fileupload.jsp</title>
</head>
<body>
uploadPath:<c:out value="${uploadPath}"></c:out><br>
<hr>
<c:forEach items="${fileNames}" var="filename">
<li><a href="${uploadPath }${filename}" class="showimg">${filename}</a></li><br>
</c:forEach>
</body>
</html>
文件上传不好看使用了bootstrap-fileinput
fileupload11.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="./jslib/bootstrap-fileinput-4.4.6/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css"/>
<link href="./jslib/bootstrap-fileinput-4.4.6/themes/explorer-fa/theme.css" media="all" rel="stylesheet" type="text/css"/>
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/plugins/sortable.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/fileinput.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/locales/fr.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/locales/es.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/themes/explorer-fa/theme.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/themes/fa/theme.js" type="text/javascript"></script>
<script type="text/javascript">
</script>
<title>fileupload.jsp</title>
</head>
<body>
<form role="form" action="fileupload/upload1.do" enctype="multipart/form-data" method="post" class="col-md-6 col-md-offset-3">
<input id="input-b0" name="file1" type="file" class="file" data-show-preview="false">
<input type="text" name="username" class="form-control" placeholder="请输入用户名" >
<input type="password" name="password" class="form-control" placeholder="请输入密码" >
<button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
</form>
</body>
</html>
fileupload12.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="./jslib/bootstrap-fileinput-4.4.6/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css"/>
<link href="./jslib/bootstrap-fileinput-4.4.6/themes/explorer-fa/theme.css" media="all" rel="stylesheet" type="text/css"/>
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/plugins/sortable.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/fileinput.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/locales/fr.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/js/locales/es.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/themes/explorer-fa/theme.js" type="text/javascript"></script>
<script src="./jslib/bootstrap-fileinput-4.4.6/themes/fa/theme.js" type="text/javascript"></script>
<script type="text/javascript">
</script>
<title>fileupload.jsp</title>
</head>
<body>
<form role="form" action="fileupload/upload2.do" enctype="multipart/form-data" method="post" class="col-md-6 col-md-offset-3">
<input id="input-b1" name="files" type="file" class="file" placeholder="文件1" data-show-preview="false">
<input id="input-b2" name="files" type="file" class="file" placeholder="文件2" data-show-preview="false">
<input id="input-b3" name="files" type="file" class="file" placeholder="文件3" data-show-preview="false">
<input type="text" name="username" class="form-control" placeholder="请输入用户名" >
<input type="password" name="password" class="form-control" placeholder="请输入密码" >
<button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
</form>
</body>
</html>
这样文件就用文件上传就会好看多了。
四、springmvc文件下载
springmvc文件下载FileDownloadController
package com.imddy.tsession.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/filedownload")
public class FileDownloadController {
private static Log log = LogFactory.getLog(FileDownloadController.class);
public static void download(String fileName, String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (fileName != null) {
File file = new File(filePath, fileName);
System.out.println("file路径:" + file);
if (file.exists()) {
// 设置强制下载不打开,也有设置成response.setContentType("application/octet-stream charset=utf-8");
response.setContentType("application/force-download charset=utf-8");
// 设置文件名
response.addHeader("Content-Disposition","attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
response.setContentLength((int) file.length());
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} else {
System.out.println("文件不存在");
}
} else {
System.out.println("下载的文件名为空");
}
}
@RequestMapping("down")
public void down(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
System.out.println("fileName: " + fileName);
System.out.println("filePath: " + filePath);
log.info("fileName: " + fileName);
log.info("filePath: " + filePath);
download(fileName, filePath, request, response);
}
}
filedownload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="./jslib/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="./jslib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="./jslib/jquery/1.12.4/jquery.min.js"></script>
<script src="./jslib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
<title>filedownload.jsp</title>
</head>
<body>
<form role="form" action="filedownload/down.do" enctype="multipart/form-data" method="post" class="col-md-6 col-md-offset-3">
<input type="text" name="fileName" placeholder="下载的文件名称">
<button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
</form>
</body>
</html>
结论: