0

Hi I am trying to download a file from server but at the end of my process I end up with only numbers and some weird characters on my browser. It's not downloading the file. I am using seam and JSF 1.2.

Here is my code:

public void writeBytesToResponse(UploadDefinition _instance, String path) {

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context .getExternalContext().getResponse();

    try {
        byte[] bytes = getFile(path);
        response.reset();
        response.setContentType(ContentType.PDF.getLabel());
        response.setContentLength(bytes.length);
        response.setHeader("Content-disposition", "attachment; filename=\"" + _instance.getFileName() + "\"");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        context.responseComplete();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
@SuppressWarnings("resource")
public byte[] getFile(String filePath) throws FileNotFoundException, IOException {
    File file = new File(filePath);
    InputStream is = new FileInputStream(file);
    long length = file.length();

    if (length > Integer.MAX_VALUE) {
        throw new IOException("File is too large " + file.getName());
    }

    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;

    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }

    is.close();
    return bytes;
}

Here I call the method:

public void downloadFile() {
    writeBytesToResponse(ud, path);
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
  • Does this method `ContentType.PDF.getLabel()` return a correct media type such as `application/pdf` (of your interest)? See also for a reference [this](http://stackoverflow.com/a/9394237/1391249) and [this](http://stackoverflow.com/a/3428207/1391249). – Tiny Dec 24 '14 at 15:56
  • Yes it returns "application/pdf". – Burak Akdeniz Dec 24 '14 at 16:16

1 Answers1

0

I got the answer, I was using <a4j:commandButton> on jsf and I changed it to <h:commandButton> then it worked. The point is not to use ajax.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332