java - 在浏览器中的新选项卡中打开文件而不是下载它?

标签 java spring-mvc cross-browser

我有一个 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);
}

以及Utility类中的downloadFiles方法定义:

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

我的代码片段下载所需的日志文件。预期的情况是所需的日志文件应在浏览器窗口中作为新选项卡打开。如何通过修改代码来实现这一点?

最佳答案

尝试以下更改,

  1. To open in a browser instead of downloading:

来自:

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

致:

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

添加target="_blank"属性

如果提交表单

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

如果是 anchor 标记

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

关于java - 在浏览器中的新选项卡中打开文件而不是下载它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767895/

相关文章:

java - 我如何退出我的应用程序?

java如何创建单例

java - Google Closure Templates 与 JSP 性能对比

2010 年 9 月 2 日的 Java SimpleDateFormat 格式。 16 :55PM

java - 下拉框 - 从 Spring MVC 模型/上下文到使用 freemarker 的表单

java - Struts 排除带有 Spring 的图案

java - 添加 HttpServletResponse/HttpServletRequest 作为方法参数时 Spring 请求挂起

css - 使用 IE8 或 9 时强制 DNN 5.6 加载 ie7

CSS Flexbox 布局 : old version (for working on old browser)

html - Flash Player z-index 和 Internet Explorer