日期:2014-05-18  浏览次数:20763 次

实现文件下载的servlet的问题!下载文件全是0KB,各位大侠救命啊!
刚学习jsp,servlet,想实现一个文件下载的servlet,结果下载下来的文件总是0KB,郁闷啊。。。下面是doGet方法里面的代码,我在目录下面放了一个名字是1.txt的文件,想测试一下到底能不能下载,结果下载保存下来的文本里面什么都没有,测试下载其他文件类型如rar也不行(contenttype已经设置成为application\octet-stream),下载下来的rar文件也是0KB,到底是那里错了啊?我都快疯了,坛子上的大侠们快拉我一把吧:(
response.setContentType(CONTENT_TYPE);

String   pathsavefile   =   "1.txt ";//要下载的文件
String   fileName   =   "1.txt ";;//保存窗口中显示的文件名

try
{
response.reset();
response.setContentType( "text/plain ");

response.setHeader( "Content-Disposition ",   "attachment;   filename=\ " "+fileName+ "\ " ");
ServletOutputStream   out   =   response.getOutputStream();
FileInputStream   inStream=new   FileInputStream(pathsavefile);
//循环取出流中的数据

byte[]   b   =   new   byte[4096];
int   len;
while((len=inStream.read(b))   !=   -1)
{
out.write(b,0,len);
out.flush();
}

inStream.close();
out.close();
}
catch   (Exception   ex)
{
System.out.println(ex.getMessage());
}


------解决方案--------------------
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.text.ParseException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class downloadServlet extends HttpServlet {


public downloadServlet() {
super();
}


public void destroy() {
super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding( "GBK ");
String path=request.getParameter( "path ");
try {

String filepath=this.getServletContext().getRealPath( " ");
File f = new File(filepath+ "/ "+path);
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); //纯下载方式
response.setContentType( "application/x-msdownload ");
response.setHeader( "Content-Disposition ", "attachment; filename= " + f.getName());
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) > 0)
out.write(buf,0,len);
br.close();
out.close();

} catch (ParseException