Koray Tugay
Koray Tugay

Reputation: 23800

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

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>

Upvotes: 1

Views: 1912

Answers (1)

sdanzig
sdanzig

Reputation: 4500

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> 

Upvotes: 2

Related Questions