Kavish
Kavish

Reputation: 21

Opening a file in browser in a new tab rather than downloading it?

I have a controller :

@RequestMapping(method = RequestMethod.POST, params = "action=downloading")
public void downloading(HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    String dbType = request
            .getParameter(JDBCConnectionUtility.DATABASE);
    String fileName = request.getParameter("fileType");
    String browserVersion = request.getHeader(Constants.BROWSER_TYPE);
    boolean bFlag = (browserVersion.toUpperCase().contains("MSIE 5.5"));

    Utility.downloadFiles(response, response.getOutputStream(), bFlag ,
            fileName);
}

And the downloadFiles method definition in Utility class :

 public static boolean downloadFiles(HttpServletResponse res,
        ServletOutputStream out, boolean bIE55, String fileName) {

    File file = new File(fileName);
    if (bIE55) {
        res.setContentType("application/download; name=\"" + file.getName()
                + "\"");
        res.setHeader("Content-Disposition",
                "anything; filename=\"" + file.getName() + "\";");
    } else {
        res.setContentType("application/octet-st" + "; name=\""
                + file.getName() + "\"");
        res.setHeader("Content-Disposition",
                "anything; filename=\"" + file.getName() + "\";");
    }
        logger.debug("stored the response");
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(file));

        int bytesRead = 0;
        byte[] byteBuff = new byte[1024];
        while ((bytesRead = bis.read(byteBuff)) > 0) {
            out.write(byteBuff, 0, bytesRead);
        }
        out.flush();
    } catch (Exception exc) {
        logger.error(exc.getStackTrace());
        return false;
    } finally {
        closeStream(bis);
    }

        logger.debug("In the download files Exit");
    return true;
}

My code snippet downloads the required log file. The expected case is that the required log file should open as a new tab in the browser window. How can I achieve this by modifying the code?

Upvotes: 2

Views: 4157

Answers (1)

0190198
0190198

Reputation: 1717

Try below changes,

  1. To open in a browser instead of downloading:

From:

 res.setHeader("Content-Disposition",
                "anything; filename=\"" + file.getName() + "\";");

To:

 res.setHeader("Content-Disposition",
                "inline; filename=\"" + file.getName() + "\";");
  1. To open in a new tab:

Add target="_blank" attribute

If in case of form submission

<form method="post" action="/urlhere"  target="_blank">

If in case of the anchor tag

<a href="/urlhere" target="_blank"/>

Upvotes: 2

Related Questions