2017-01-23 6 views
0

こんにちは私はExcelシートを生成し、ユーザーがダウンロードボタンをクリックするとダウンロードできるようにコードを書こうとしています....私はExcelシートしかし、私は同じをダウンロードしようとしたが、私は失敗しました。JSFを使用してExcelファイルをダウンロードできない

私が使用している方法は次のとおりです。

public void download() throws IOException { 
    File file = new File("D:\\pdf\\carrierReport7.xls"); 

    FacesContext facesContext = FacesContext.getCurrentInstance(); 

    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); 

    response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); 
    response.setHeader("Content-Type", "application/vnd.ms-excel"); 

    OutputStream outputStream = response.getOutputStream(); 

    FileInputStream fileInputStream = new FileInputStream(file); 

    byte[] bytesBuffer = new byte[2048]; 

    int bytesRead = 0; 

    while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0) { 
     outputStream.write(bytesBuffer, 0, bytesRead); 
    } 

    outputStream.flush(); 

    fileInputStream.close(); 
    outputStream.close(); 

    facesContext.responseComplete(); 
} 

JSFコマンド:

+1

エラー/例外が表示されますか?これを試しても実際にブラウザにダウンロードするものはありますか? –

+0

duploverの1つをstackoverflowで見つけて、それらのどの部分が役立つかを確認してください。そしてニコラススミスは正しいです...あなたはもっと情報を提供することができます。 – Kukeltje

+0

エラーはありません。要求を処理するだけで応答はありません。何もダウンロードしていません。私はすでに異なるコードをstackoverflowで与えられた試みたが、私は同じ問題に直面している。私はweb.xmlやブラウザの設定を変更する必要があります –

答えて

0

私はJSF 2に似た何かをやっているどのようにこれは、どのバージョンあなたは上のわかりません。

public void downloadAttachment(Attachment attachment) throws IOException { 
    FacesContext fc = FacesContext.getCurrentInstance(); 
    ExternalContext ec = fc.getExternalContext(); 

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide. 
    ec.setResponseContentType(ec.getMimeType(attachment.getFilename()));   
    ec.setResponseContentLength(attachment.getFilesizeBytes().intValue()); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown. 
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + attachment.getFilename() + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead. 

    OutputStream output = ec.getResponseOutputStream(); 
    output.write(attachment.getFileData()); 

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. } 

} 
+0

私はあなたがコードの言及を試みたが、同じ問題がまだあります。それは何もダウンロードされていません。 –

関連する問題