servlet的文件上传和下载
1.准备工作和前提条件
ide工具使用的是eclipse(自我感觉eclipse建普通的servlet的项目比idea简洁轻便)
使用tomcat版本是7
使用的servlet是2.5(建议使用这个版本,是xml配置版本)
2.新建上传文件的文件夹
在webcontent目录下新建文件夹uploadFile
这个文件夹测试文件上传和下载的文件夹
3.导入相关的依赖
commons-fileupload-1.2.1.jar
commons-io-1.4.jar
4.准别测试文件
(1)oracle.md
(2)commons-beanutils-1.9.3-bin.zip
(3)Koala.jpg
为了测试全面,我测试三种文件格式,一个是.md文档,一个是压缩文件,一个是图片
5.编写servlet
5.1文件上传
文件上传servlet
package com
.shaoming
.servlet
;
import java
.io
.File
;
import java
.io
.*
;
import java
.io
.IOException
;
import java
.io
.PrintWriter
;
import java
.util
.List
;
import javax
.servlet
.ServletContext
;
import javax
.servlet
.ServletException
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import org
.apache
.catalina
.tribes
.util
.Arrays
;
import org
.apache
.commons
.fileupload
.FileItem
;
import org
.apache
.commons
.fileupload
.FileUploadException
;
import org
.apache
.commons
.fileupload
.disk
.DiskFileItemFactory
;
import org
.apache
.commons
.fileupload
.servlet
.ServletFileUpload
;
import cn
.hutool
.core
.io
.FileUtil
;
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
request
.setCharacterEncoding("utf-8");
DiskFileItemFactory factory
= new DiskFileItemFactory();
String path
= request
.getSession().getServletContext().getRealPath("/uploadFile") + File
.separator
;
File
[] ls
= FileUtil
.ls(path
);
System
.out
.println(Arrays
.toString(ls
));
System
.out
.println(path
);
factory
.setRepository(new File(path
));
factory
.setSizeThreshold(1024 * 1024);
ServletFileUpload upload
= new ServletFileUpload(factory
);
try {
List
<FileItem> list
= (List
<FileItem>) upload
.parseRequest(request
);
for (FileItem item
: list
) {
String name
= item
.getFieldName();
if (item
.isFormField()) {
String value
= item
.getString();
request
.setAttribute(name
, value
);
} else {
String value
= item
.getName();
int start
= value
.lastIndexOf("\\");
String filename
= value
.substring(start
+ 1);
request
.setAttribute(name
, filename
);
OutputStream out
= new FileOutputStream(new File(path
,
filename
));
InputStream in
= item
.getInputStream();
int length
= 0;
byte[] buf
= new byte[1024];
System
.out
.println("获取上传文件的总共的容量:" + item
.getSize());
while ((length
= in
.read(buf
)) != -1) {
out
.write(buf
, 0, length
);
}
in
.close();
out
.close();
}
}
} catch (FileUploadException e
) {
e
.printStackTrace();
} catch (Exception e
) {
}
}
}
说明:
String path = request.getSession().getServletContext().getRealPath("/uploadFile") + File.separator;
这个path就是上传文件的路径
上传文件的jsp页面 upload.jsp(放在项目的WebContent目录下)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Jsp+Servlet upload file</title>
</head>
<body>
<form action="/java-web/UploadServlet" method="POST" enctype="multipart/form-data">
<input type ="file" name="file1" id="file1"/><br/>
<input type ="file" name="file2" if="file2"/><br/>
<input type ="file" name="file3" id="file3"/><br/>
<input type="submit" value="Submit" /><br/>
<input type="reset" />
</form>
</body>
</html>
说明:
(1)form表单的请求方式必须是post
(2)form表单加入属性enctype=“multipart/form-data” 表示可以提交文件
5.2文件下载
文件下载的servlet
package com
.shaoming
.servlet
;
import java
.io
.File
;
import java
.io
.FileInputStream
;
import java
.io
.IOException
;
import java
.io
.InputStream
;
import java
.io
.OutputStream
;
import javax
.servlet
.ServletException
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
public class ServletDownload extends HttpServlet {
public ServletDownload() {
super();
}
public void doGet(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
String filename
= request
.getParameter("filename");
System
.out
.println(filename
);
response
.setContentType(getServletContext().getMimeType(filename
));
response
.setHeader("Content-Disposition", "attachment;filename="+filename
);
String path
= request
.getSession().getServletContext().getRealPath("/uploadFile") + File
.separator
;
String fullFileName
= path
+"//"+ filename
;
System
.out
.println(fullFileName
);
InputStream in
= new FileInputStream(fullFileName
);
OutputStream out
= response
.getOutputStream();
int b
;
while((b
=in
.read())!= -1)
{
out
.write(b
);
}
in
.close();
out
.close();
}
public void doPost(HttpServletRequest request
, HttpServletResponse response
)
throws ServletException
, IOException
{
}
}
下载文件的jsp页面downloadTwo.jsp(放在项目的WebContent目录下)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="UTF-8">
<title>通过链接下载文件</title>
</head>
<body>
<h1>通过链接下载文件</h1>
<a href="/java-web/uploadFile/commons-beanutils-1.9.3-bin.zip">压缩包</a>
<a href="/java-web/uploadFile/Koala.jpg">图片</a>
<a href="/java-web/uploadFile/oracle.md">.md文档</a>
<h1>通过servlet程序下载文件</h1>
<a href="/java-web/ServletDownload?filename=commons-beanutils-1.9.3-bin.zip">压缩包</a>
<a href="/java-web/ServletDownload?filename=Koala.jpg">图片</a>
<a href="/java-web/ServletDownload?filename=oracle.md">.md文档</a>
</body>
</html>
说明:
为了简便测试,就是用超链接的方式对文件进行下载操作
6.打包部署测试
eclipse导报动态的web工程(就是servlet的项目)
1.打包
步骤
右击项目—>export—>选择web/WARfile—>next—>选择打包路径–>next—>打包成功
2.部署
把war包放到tomcat的webapp目录,启动tomcat
3.测试文件上传的url路径
localhost:8080/java-web/upload.jsp
4.测试文件下载的url路径
localhost:8080/java-web/downloadTwo.jsp