下载文件的SERVLET
类别: JSP教程
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Download extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
//这里你可以做些其他的事情
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="你要在保存窗口中显示的保存文件名"");
ServletOutputStream out = response.getOutputStream();
BufferedReader br=new BufferedReader(new FileReader(要下载的的文件名));
String line=br.readLine();
while (line!=null)
{
out.write(line.getBytes());
out.println();
line=br.readLine();
}
out.close();
br.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
doGet(request, response);
}
}
就是这么简单
版主提示:
这里的代码在做二进制文件下载的时候会有问题,因为这里使用到了BufferedReader,而这个类是为读“字符”而准备,需要按“字节”来读的时候,请使用InputStream来做。
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Download extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
//这里你可以做些其他的事情
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="你要在保存窗口中显示的保存文件名"");
ServletOutputStream out = response.getOutputStream();
BufferedReader br=new BufferedReader(new FileReader(要下载的的文件名));
String line=br.readLine();
while (line!=null)
{
out.write(line.getBytes());
out.println();
line=br.readLine();
}
out.close();
br.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
doGet(request, response);
}
}
就是这么简单
版主提示:
这里的代码在做二进制文件下载的时候会有问题,因为这里使用到了BufferedReader,而这个类是为读“字符”而准备,需要按“字节”来读的时候,请使用InputStream来做。
-= 资 源 教 程 =-
文 章 搜 索