当前位置:编程学习 > JSP >>

下载文件的servlet(很简单的)

答案: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来做。 

上一个:JSP中的TagLib应用(4)--zt
下一个:Java web应用开发概览(转贴)

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,