开发者

downloading excel sheet from servlet response

I am trying to download an excel sheet from servlet response.

When I click on link which sends request to server for returning an excel sheet, save/save as dialog box gets opened asking to save 开发者_Python百科the excel sheet. This is an expected behavior.

But in between, if I try to use IE 6 or below version, then it opens up new window after clicking on the link. And then opens up Save/Save As dialog box.

Other operations run as expected, but the problem is, the new window displays the message Can't open the page.

Is there any way, I can avoid opening of this new window?

I want Save/Save As dialog box directly appear in the same window from which link has been clicked.


If you want to send a response from a servlet (or in fact any web app) that shall be treated as a download, you can do so by giving the right content-disposition (you can even specify the filename independent of the URI):

HttpServletResponse res = ...
/*
 * set headers
 */
res.setContentType("application/vnd.ms-excel");
res.setHeader("Content-Disposition", "attached; filename=my-workbook.xls");
/*
* pass the download to the response
*/
try {
    OutputStream out = res.getOutputStream();
    InputStream in = this.download.getInputStream();
    byte[] buffer = new byte[res.getBufferSize()];
    int available = in.read(buffer);
    while (available > 0) {
        out.write(buffer, 0, available);
        available = in.read(buffer);
    }
    in.close();
    out.flush();
    out.close();
} catch (IOException e) {
    // handle exception
}


I've seen the new window opened a lot of times, but never an error inside it.

Try launching the download in an IFrame. If the download itself still triggers that might help to hide the error message. It would be better to figure out why the error is displaying and stop it, but if that fails you might at least be able to hide it from the user.

Though I have seen IE do weird things with errors in IFrames before (it'll framebust occasionally), but I think that was only related to non-standard protocol handlers, not HTTP errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜