Downloading files from Servlets - Chrome warning + how to redirect user after download?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 06:57:05

问题


I have a simple table with downlod file links..

Everything seems to work fine, when I click download, the file is found on the harddrive and served to the user.

My problem is, when I inspect chrome I see:

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

Why would it say that?

The relevant code I have is:

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

Also a bonus question:

After the file is downloaded, the user still sees the page with the table, but I want to redirect to a different page. How can I do that?

 response.sendRiderect() 

does not seem to work.

Edit: This is how I provide download link to the user:

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

回答1:


Try specifying the HTML5 download attribute in your download link:

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

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

As for the redirect, not good news here 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.

So you won't be able to do anything more with the response after you've sent the file (which is a committed response). However, you could forward them onto another page first, and then have that display a message and eventually trigger the download.

Found this example:

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


来源:https://stackoverflow.com/questions/19596657/downloading-files-from-servlets-chrome-warning-how-to-redirect-user-after-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!