如何从后端Java代码发送PDF文件?

发布于 2024-12-21 14:26:54 字数 67 浏览 1 评论 0原文

我有一个 JSP 文件,有后端帮助程序类。我需要从后端助手将 PDF 文件作为附件发送到 JSP。我怎样才能做到这一点?

I have a JSP file, there backend helper class to it. From the back end helper I need to send PDF file to the JSP as an attachment. How can I achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

姐不稀罕 2024-12-28 14:26:54

我建议您使用 Apache Commons File Upload 组件。这可能是最好的方法,而不是重新发明轮子。 ;)

I would suggest you to use Apache Commons File Upload component. That's probably the best way rather than reinventing the wheel. ;)

空城旧梦 2024-12-28 14:26:54

由于您没有告诉我们您是否使用任何 MVC 框架或只是简单的 Servlet,因此我将介绍基础知识。

如果您想上传文件,Apache Commons File Upload 是最好的库,它将翻译您的 multipart/form-data 编码的 HttpServletRequest 消息,并为您提供上传的文件(在InputStream 格式,大多是首选)。

作为开发人员,您可以将数据写回到您选择的持久存储中。

相反,它获取文件,获取适当的 MIME-Type、Content-Length(文件大小)和文件数据(InputStream,如果可能)并将其渲染回 HttpServletResponse )。

这段代码(功能齐全,由我编写)确实将文件作为附件/内联。

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Buhake Sindi (The Elite Gentleman)
 * @since 01 September 2011
 */
public class FileServletRenderer implements ServletRenderer {

  private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB
  private static final String OCTECT_STREAM_MIME_TYPE = "application/octect-stream";
  private String contentType = OCTECT_STREAM_MIME_TYPE;
  private long contentLength;
  private String contentDisposition = "inline";
  private String fileName;
  private InputStream inputStream;

  /**
   * @return the contentType
   */
  public String getContentType() {
    return contentType;
  }

  /**
   * @param contentType
   *          the contentType to set
   */
  public void setContentType(String contentType) {
    this.contentType = contentType;
  }

  /**
   * @return the contentLength
   */
  public long getContentLength() {
    return contentLength;
  }

  /**
   * @param contentLength
   *          the contentLength to set
   */
  public void setContentLength(long contentLength) {
    this.contentLength = contentLength;
  }

  /**
   * @return the contentDisposition
   */
  public String getContentDisposition() {
    return contentDisposition;
  }

  /**
   * @param contentDisposition
   *          the contentDisposition to set
   */
  public void setContentDisposition(String contentDisposition) {
    this.contentDisposition = contentDisposition;
  }

  /**
   * @return the fileName
   */
  public String getFileName() {
    return fileName;
  }

  /**
   * @param fileName
   *          the fileName to set
   */
  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  /**
   * @return the inputStream
   */
  public InputStream getInputStream() {
    return inputStream;
  }

  /**
   * @param inputStream
   *          the inputStream to set
   */
  public void setInputStream(InputStream inputStream) {
    this.inputStream = inputStream;
  }

  public void setFile(File file) throws IOException {
    if (file == null) {
      throw new IOException("file is null.");
    }

    setInputStream(new BufferedInputStream(new FileInputStream(file)));
    setContentLength(file.length());
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.bfs.bayweb.util.renderer.ServletViewRenderer#render(javax.servlet.
   * ServletRequest, javax.servlet.ServletResponse)
   */
  public void render(ServletRequest request, ServletResponse response) throws IOException {
    // TODO Auto-generated method stub
    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

    try {
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int inputStreamLength = 0;
      int length = 0;

      if (contentType == null) {
        contentType = request.getServletContext().getMimeType(getFileName());
      }

      //We couldn't determine Content-Type
      if (contentType == null) {
        contentType = OCTECT_STREAM_MIME_TYPE;
      }

      while ((length = getInputStream().read(buffer)) > 0) {
        inputStreamLength += length;
        bos.write(buffer, 0, length);
      }

      if (inputStreamLength != getContentLength()) {
        setContentLength(inputStreamLength);
      }

      if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.reset();
        httpResponse.setHeader("Content-Type", getContentType());
        httpResponse.setHeader("Content-Length", String.valueOf(getContentLength()));
        httpResponse.setHeader("Content-Disposition", "\"" + getContentDisposition() + "\""
            + ((getFileName() != null && !getFileName().isEmpty()) ? "; filename=\"" + getFileName() + "\"" : ""));
        httpResponse.setHeader("Content-Type", getContentType());
      }

      // finally
      bos.flush();

      // clear
    } finally {
      // TODO Auto-generated catch block
      close(bos);
      close(getInputStream());
    }
  }

  private void close(Closeable resource) throws IOException {
    if (resource != null) {
      resource.close();
    }
  }
}

最重要的方法是render(HttpServletRequest, HttpServletResponse)

Since you haven't told us if you're using any MVC framework or just plain Servlet, I'll go for the basics.

If you want to upload a file, Apache Commons File Upload is the best library that will translate your multipart/form-data encoded HttpServletRequest message and provide you with files uploaded (in InputStream format, mostly preferred).

It's up to you, the developer, to write the data back to a persistent storage of your choice.

The reverse, it's to take the file, get the appropriate MIME-Type, Content-Length (file size), and file data (InputStream, if possible) and render it back to the HttpServletResponse).

This code (fully functional and written by me) does put the file as attachment/inline.

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Buhake Sindi (The Elite Gentleman)
 * @since 01 September 2011
 */
public class FileServletRenderer implements ServletRenderer {

  private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB
  private static final String OCTECT_STREAM_MIME_TYPE = "application/octect-stream";
  private String contentType = OCTECT_STREAM_MIME_TYPE;
  private long contentLength;
  private String contentDisposition = "inline";
  private String fileName;
  private InputStream inputStream;

  /**
   * @return the contentType
   */
  public String getContentType() {
    return contentType;
  }

  /**
   * @param contentType
   *          the contentType to set
   */
  public void setContentType(String contentType) {
    this.contentType = contentType;
  }

  /**
   * @return the contentLength
   */
  public long getContentLength() {
    return contentLength;
  }

  /**
   * @param contentLength
   *          the contentLength to set
   */
  public void setContentLength(long contentLength) {
    this.contentLength = contentLength;
  }

  /**
   * @return the contentDisposition
   */
  public String getContentDisposition() {
    return contentDisposition;
  }

  /**
   * @param contentDisposition
   *          the contentDisposition to set
   */
  public void setContentDisposition(String contentDisposition) {
    this.contentDisposition = contentDisposition;
  }

  /**
   * @return the fileName
   */
  public String getFileName() {
    return fileName;
  }

  /**
   * @param fileName
   *          the fileName to set
   */
  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  /**
   * @return the inputStream
   */
  public InputStream getInputStream() {
    return inputStream;
  }

  /**
   * @param inputStream
   *          the inputStream to set
   */
  public void setInputStream(InputStream inputStream) {
    this.inputStream = inputStream;
  }

  public void setFile(File file) throws IOException {
    if (file == null) {
      throw new IOException("file is null.");
    }

    setInputStream(new BufferedInputStream(new FileInputStream(file)));
    setContentLength(file.length());
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.bfs.bayweb.util.renderer.ServletViewRenderer#render(javax.servlet.
   * ServletRequest, javax.servlet.ServletResponse)
   */
  public void render(ServletRequest request, ServletResponse response) throws IOException {
    // TODO Auto-generated method stub
    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

    try {
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int inputStreamLength = 0;
      int length = 0;

      if (contentType == null) {
        contentType = request.getServletContext().getMimeType(getFileName());
      }

      //We couldn't determine Content-Type
      if (contentType == null) {
        contentType = OCTECT_STREAM_MIME_TYPE;
      }

      while ((length = getInputStream().read(buffer)) > 0) {
        inputStreamLength += length;
        bos.write(buffer, 0, length);
      }

      if (inputStreamLength != getContentLength()) {
        setContentLength(inputStreamLength);
      }

      if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.reset();
        httpResponse.setHeader("Content-Type", getContentType());
        httpResponse.setHeader("Content-Length", String.valueOf(getContentLength()));
        httpResponse.setHeader("Content-Disposition", "\"" + getContentDisposition() + "\""
            + ((getFileName() != null && !getFileName().isEmpty()) ? "; filename=\"" + getFileName() + "\"" : ""));
        httpResponse.setHeader("Content-Type", getContentType());
      }

      // finally
      bos.flush();

      // clear
    } finally {
      // TODO Auto-generated catch block
      close(bos);
      close(getInputStream());
    }
  }

  private void close(Closeable resource) throws IOException {
    if (resource != null) {
      resource.close();
    }
  }
}

The most important method is render(HttpServletRequest, HttpServletResponse).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文