【问题标题】:Opening a file in browser in a new tab rather than downloading it?在新选项卡中的浏览器中打开文件而不是下载文件?
【发布时间】:2018-01-27 19:17:52
【问题描述】:

我有一个控制器:

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

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

【问题讨论】:

    标签: java spring-mvc cross-browser


    【解决方案1】:

    尝试以下更改,

    1. 在浏览器中打开而不是下载:

    发件人:

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

    收件人:

     res.setHeader("Content-Disposition",
                    "inline; filename=\"" + file.getName() + "\";");
    
    1. 在新标签页中打开:

    添加target="_blank"属性

    如果在表单提交的情况下

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

    如果在锚标签的情况下

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

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 2019-03-08
      • 2011-10-18
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      相关资源
      最近更新 更多