热点推荐:ASP.Net | ADO.Net | VB.Net | Web服务器 | Access | MSSQL | MySQL | Oracle | .Net控件 | Win 9x | Win 2000 | Win 2003 | DOS | Unix | 注册表 | 应用其它 | 安装调试 | 基本操作 | 使用技巧 | 系统优化 |故障处理 | 个性风格 | 病毒安全 | 专杀工具
您现在的位置: 中华IT技术网 >> Java >> J2EE >> 正文
全文
发送PDF文件
作者:1024k    文章来源:本站原创    更新时间:2007-11-21

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

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

public class UrlServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
      throw new ServletException(
          "Invalid or non-existent file parameter in UrlServlet servlet.");

    if (fileName.indexOf(".pdf") == -1)
      fileName = fileName + ".pdf";

    URL pdfDir = null;
    URLConnection urlConn = null;
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {

      pdfDir = new URL(getServletContext().getInitParameter(
          "remote-pdf-dir")
          + fileName);

    } catch (MalformedURLException mue) {

      throw new ServletException(mue.getMessage());
    }
    try {

      stream = response.getOutputStream();

      //set response headers
      response.setContentType("application/pdf");
      response.addHeader("Content-Disposition", "attachment; filename="
          + fileName);

      urlConn = pdfDir.openConnection();
      response.setContentLength((int) urlConn.getContentLength());

      buf = new BufferedInputStream(urlConn.getInputStream());
      int readBytes = 0;

      //read from the file; write to the ServletOutputStream
      while ((readBytes = buf.read()) != -1)
        stream.write(readBytes);
    } catch (IOException ioe) {
      throw new ServletException(ioe.getMessage());
    } fina
 

lly {
      if (stream != null)
        stream.close();
      if (buf != null)
        buf.close();
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    doGet(request, response);
  }
}

  • 上一篇文章:
  • 下一篇文章:
  • 相关文章
    最新更新
    编辑推荐
    热门图片
    频道大全
    文章阅读排行
    周排行
    月排行