file_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>
</head>
<body>
<h1>文件上传</h1>
<form action="FileUploadDemo" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="uname"><br>
上传文件:<input type="file" name="fileupload"><br>
<input type="submit" value="上传朋友圈">
</form>
</body>
</html>
public class FileUploadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 准备:导入两个jar包&页面3处
1. 创建工厂类
2. 创建解析器ServletFileUpload
3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
4. FileItem中的write()方法,写到服务器。
*/
//1. 创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//2. 创建解析器ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//获取upload的真实路径
String realPath = this.getServletContext().getRealPath("/upload");
System.out.println(realPath);
//3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
try {
List<FileItem> list = upload.parseRequest(request);
//迭代集合,查找指定的文件
for (FileItem fileItem : list) {
if(fileItem.isFormField() == false){
String filePath = realPath+"/"+fileItem.getName();
File file = new File(filePath);
//4. FileItem中的write()方法,写到服务器
fileItem.write(file);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().write("upload success!");
//获取参数
// String username = request.getParameter("uname");
// String fileupload = request.getParameter("fileupload");
//
// System.out.println(username);
// System.out.println(fileupload);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
注意:此时会将文件复制到当前项目所在服务器目录下/upload目录下!
优化上传问题
public class FileUploadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
//1. 创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//2. 创建解析器ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//获取upload的真实路径
String realPath = this.getServletContext().getRealPath("/upload");
// System.out.println(realPath);
//设置单个文件的上传大小
upload.setFileSizeMax(2*1024);
//3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
try {
List<FileItem> list = upload.parseRequest(request);
//迭代集合,查找指定的文件
for (FileItem fileItem : list) {
if(fileItem.isFormField() == false){
String uuid = UUID.randomUUID().toString().replace("-", "");
String filePath = realPath+"/"+uuid+fileItem.getName();
File file = new File(filePath);
//4. FileItem中的write()方法,写到服务器
fileItem.write(file);
}
}
}catch (FileSizeLimitExceededException e) {
writer.write("单个文件大小不能超过2k");
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
file_download.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>
</head>
<body>
<h1>宝库</h1>
<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=music.mp3">music.mp3</a>
<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=picture.jpg">picture.jpg</a>
<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=china.txt">china.txt</a>
<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=邓紫棋.mp4">邓紫棋.mp4</a>
</body>
</html>
public class FileDownLoadDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// response.setContentType("text/html;charset=UTF-8");
//获取文件名
String fileName = request.getParameter("fileName");
//通过fileName获取该文件的真实路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/download");
String downloadPth = realPath+"/"+fileName;
System.out.println(downloadPth);
//设置浏览器响应体文件类型
String mimeType = request.getServletContext().getMimeType(fileName);
response.setContentType(mimeType);
//解决文件名中文乱码问题
String header = request.getHeader("User-Agent");
if(header != null && header.contains("Firefox")) {
fileName = "=?utf-8?B?"+new BASE64Encoder().encode(fileName.getBytes("utf-8"))+"?=";
}else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
//设置浏览器响应体内容格式,为附件格式。(告诉浏览器别播放,下载)
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
//读取目标资源,同时写到客户端(下载)
//创建读入流
FileInputStream fis = new FileInputStream(downloadPth);
//创建写出流
ServletOutputStream ops = response.getOutputStream();
byte[] b = new byte[1024];
while(fis.read(b) != -1){
ops.write(b);
}
ops.close();
fis.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
注意:当在servlet中设置setContextType(“text/html;charset=UTF-8”)时,只能读取txt文件,需要设置浏览器响应文件类型、解决中文乱码问题、设置浏览器响应格式!