0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user1097291
  • 11
  • 1
  • 3

2 Answers2

0

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

Daniel Baktiar
  • 1,692
  • 11
  • 22
  • There is a prolem in it. It always use servlet for uploading the pdf. My problem is I have to do upload the pdf from backend java code(Helper java class) – user1097291 Dec 14 '11 at 07:34
  • If I understand your requirement correctly, you need a client library to connect to a server (which is your own servlet). You can use the Apache Commons File Upload, it is a client library that you can use to implement the requirement. CMIIW... – Daniel Baktiar Dec 14 '11 at 11:05
  • Or are you asking a better way to simulate upload, but not through the servlet front end? In that case you need to open a stream. Depends on how the backend receives the data, probably in a BLOB? You can open a stream and feed the PDF directly to the blob stream then. – Daniel Baktiar Dec 14 '11 at 11:06
0

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).

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • Why don't you just write input to output immediately? – BalusC Dec 14 '11 at 13:30
  • You could, but I wrote this for MVC based (action) form beans. I extracted the relevant ones for this post only. – Buhake Sindi Dec 14 '11 at 13:53
  • 1
    No, I mean the unnecessary `ByteArrayOutputStream`. You're basically copying the whole file fully in server's memory first which is memory hogging on large files and lot of requests. – BalusC Dec 14 '11 at 13:56