gpt4 book ai didi

java - 从 Servlet 下载文件 - Chrome 警告 + 下载后如何重定向用户?

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

我有一个带有下载文件链接的简单表格..

一切似乎都工作正常,当我单击下载时,会在硬盘驱动器上找到该文件并将其提供给用户。

我的问题是,当我检查 chrome 时,我看到:

Resource interpreted as Document but transferred with MIME type application/octet-stream: "http://localhost:8080/fus-app/myUploadedFiles".

为什么会这么说呢?

我拥有的相关代码是:

    httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameOnSystem + "\"");

还有一个额外问题:

下载文件后,用户仍然看到带有表格的页面,但我想重定向到不同的页面。我怎样才能做到这一点?

 response.sendRiderect() 

似乎不起作用。

编辑:这就是我向用户提供下载链接的方式:

<form method="post" action="<%= request.getServletContext().getContextPath() +"/myUploadedFiles" %>">
<input type="hidden" name="fileNameOnSystem" value="<%= rset.getString("fileNameOnSystem") %>" />
<button type="submit" class="btn btn-default" />Download File </button>
</form>

最佳答案

尝试在下载链接中指定 HTML5 下载属性:

<a href='http://example.com/archive.zip' download>Export</a>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download

至于重定向,这里不是好消息 Is it possible to forward or redirect from a servlet filter after the response has been committed? ...

The "committed" status of an HttpServletResponse is really a way of saying whether the response headers have been written to the underlying socket. A "committed" response has had (at least) the first line written. Since the first line of the response contains the status code, it follows that you cannot change the status code of a committed response ... and that means it is too late to change the status to 3xx to do a redirect. Similarly, you cannot do a local forward because you've already started sending the response.

因此,在发送文件(这是已提交的响应)后,您将无法对响应执行任何操作。但是,您可以先将它们转发到另一个页面,然后显示一条消息并最终触发下载。

找到这个例子:

<html>  
<head>
<meta http-equiv="refresh" content="5;url=http://server.com/file.zip">
</head>
<body>
Thank you for downloading file.zip!
</body>
</html>

关于java - 从 Servlet 下载文件 - Chrome 警告 + 下载后如何重定向用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19596657/

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