使用JSF下载文件 [英] Downloading a file using JSF

查看:64
本文介绍了使用JSF下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器下载文件,但是在我的过程结束时,我最终在浏览器中只看到数字和一些奇怪的字符.它没有下载文件.我正在使用seam和JSF 1.2.

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.

这是我的代码:

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

推荐答案

我得到了答案,我在jsf上使用了<a4j:commandButton>,我将其更改为<h:commandButton>,然后它起作用了.重点是不要使用ajax.

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.

这篇关于使用JSF下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆