servlet(文件下载简单demo)
实现了一个小小的文件下载demo,记录一下,(伟大的项目,都是从一个有一个小小的demo垒起来的)
首先来看下我的project Explorer
画红线的是用不着的类。。。。。。不用管它
接下来,让我们src目录下的代码
com.zhu.Tset中的Servlet1.java
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得想要下载文件的名称
String filename = request.getParameter("filename");
//要下载的文件类型---客户端通过MIME来区分文件类型
response.setContentType(this.getServletContext().getMimeType(filename));
//告诉客户端不是直接解析,而是下载下来
response.setHeader("Content-Disposition","attachment;filename+"+filename);
//获取文件的路径
String path = this.getServletContext().getRealPath("download/"+filename);
//获得该文件的输入流
InputStream in = new FileInputStream(path);
//获得输出流,用于向客户端写内容
OutputStream out = response.getOutputStream();
//文件拷贝模版
int len = 0;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0) {
out.write(buffer, 0, len);
}
in.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
在WebContent中创建一个文件夹叫download里面分别拷贝进去如图的一些格式的文件
web.xml的配置
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Web2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Servlet1</display-name>
<servlet-name>Servlet1</servlet-name>
<servlet-class>com.zhu.Tset.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
download.html 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>使用a标签直接指向服务器上的资源</h1>
<a href="/Web2/download/timg.jpg">a.jpg</a><br>
<a href="/Web2/download/timg.flv">a.flv</a><br>
<a href="/Web2/download/timg.avi">a.avi</a><br>
<a href="/Web2/download/timg.txt">a.txt</a><br>
<a href="/Web2/download/timg.mp3">a.mp3</a><br>
<h1>使用a标签下载服务器上的资源</h1>
<a href="/Web2/servlet1?filename=timg.jpg">a.jpg</a><br>
<a href="/Web2/servlet1?filename=timg.flv">a.flv</a><br>
<a href="/Web2/servlet1?filename=timg.avi">a.avi</a><br>
<a href="/Web2/servlet1?filename=timg.txt">a.txt</a><br>
<a href="/Web2/servlet1?filename=timg.mp3">a.mp3</a><br>
</body>
</html>
最后实现效果