gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:25:18 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com