使用JSF下载文件

时间:2014-12-24 15:53:25

标签: jsf download jsf-1.2

您好我正在尝试从服务器下载文件,但在我的过程结束时,我的浏览器上只有数字和一些奇怪的字符。它没有下载文件。我正在使用seam和JSF 1.2。

这是我的代码:

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;
}

我在这里称呼方法:

public void downloadFile() {
    writeBytesToResponse(ud, path);
}

1 个答案:

答案 0 :(得分:0)

我得到了答案,我在jsf上使用了<a4j:commandButton>并将其更改为<h:commandButton>然后就可以了。关键是不要使用ajax。