You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@tomcat.apache.org by Léa Massiot <lm...@orange.fr> on 2014/09/25 11:48:05 UTC
File download using a servlet and error handling
Hello and thank you for reading my post.
My question is about downloading a file using a servlet and handling
possible errors that may take place during the download process.
1) I have a JSP page "download-file.jsp" with a "Download file" button:
======================================================
<form method="post" action="do_download_file">
[...]
<input type="submit" name="download_file" id="download_file"
value="Download file" />
[...]
</form>
======================================================
When this button is hit by a user, the "doPost()" method of the servlet
mapped with the action "do_download_file" is executed.
It includes a call to the method below.
2) Everywhere on the Web one can find that type of code (for the file
downloading):
======================================================
public boolean downloadFile(String s_fileNameAndPath, String s_fileName,
HttpServletResponse httpServletResponse)
throws IOException, SQLException, ClassNotFoundException, ModelException
{
File file = null;
long l_fileLength = -1;
ServletOutputStream servletOutputStream = null;
int n_bufsize = 4096;
DataInputStream dataInputStream = null;
int n_nbBytesRead = -1;
boolean b_anErrorOccurred = false;
byte[] byteBuffer;
file = new File(s_fileNameAndPath);
l_fileLength = file.length();
if(l_fileLength <= 0)
{
b_anErrorOccurred = true;
return b_anErrorOccurred;
}
n_nbBytesRead = 0;
byteBuffer = new byte[n_bufsize];
servletOutputStream = httpServletResponse.getOutputStream();
httpServletResponse.setContentType("text/html");
httpServletResponse.setContentLength((int) l_fileLength);
httpServletResponse.setHeader("Content-Disposition", "attachment;
filename=\"" + s_fileName + "\"");
dataInputStream = new DataInputStream(new FileInputStream(file));
while((dataInputStream != null)
&& ((n_nbBytesRead = dataInputStream.read(byteBuffer)) != -1))
{
servletOutputStream.write(byteBuffer, 0, n_nbBytesRead);
servletOutputStream.flush();
}
if(true)
{
throw new ModelException("To provoke an error on purpose.");
}
dataInputStream.close();
servletOutputStream.close();
return b_anErrorOccurred;
}
======================================================
(Apart from the exception being thrown) this code works: it actually
downloads the targeted file.
You may have noticed that in the method above, I deliberately throw an
exception so that I can test error handling.
My problem is that, with this way of doing things, I can't tell the user
that the download operation failed since the "HttpServletResponse" has
already been "consumed" when the method returns...
My question is:
Ideally, after the download, I wish I could go back to the JSP
"download-file.jsp" so that I can tell the user that an error occurred while
downloading the file.
If the download was successful, I also would like to tell the user that
everything went right...
I don't see how I can both download the file and redirect the user towards
the "download-file.jsp" page with an appropriate message.
Do you have an idea how I should proceed?
All the best and sorry for the language approximations like "consumed", etc.
--
View this message in context: http://tomcat.10.x6.nabble.com/File-download-using-a-servlet-and-error-handling-tp5023017.html
Sent from the Tomcat - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by Léa Massiot <lm...@orange.fr>.
Ok guys, thank you all: I understand better. I'll see what I can do.
Best regards.
--
View this message in context: http://tomcat.10.x6.nabble.com/File-download-using-a-servlet-and-error-handling-tp5023017p5023118.html
Sent from the Tomcat - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Hassan,
On 9/25/14 11:28 AM, Hassan Schroeder wrote:
> On Thu, Sep 25, 2014 at 7:18 AM, Léa Massiot <lm...@orange.fr>
> wrote:
>
>> I was thinking maybe about an "error-page"... (never done that
>> before): in case an exception is thrown after the response "has
>> been committed", maybe this error page could be sent to the
>> user...
>
> Since the user's browser will still be displaying
> "download-file.jsp" after the download, why not add some JS/AJAX to
> the page to poll for a status update and display that?
>
> Just another possibility :-)
This is what I did for a client some years back who wanted to show a
download progress bar without a native download client. We did it with
HTTP refreshes and no Javascript (pre-AJAX days).
- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1
Comment: GPGTools - http://gpgtools.org
iQIcBAEBCAAGBQJUJGXSAAoJEBzwKT+lPKRYy94QAJO958H6vXkFiw27ATO/6ALK
+30Kkz2O7mJK/k5Z5xKhbzwcwoO0KzOGF1dQSC/Lvz/5DhfJ7oLkZ+6XXZFuPweF
78rCF/M89jMEfdli0vPJN2fw9js1CuSOqzrNUzJz+LZx7dgqLjvu94pF9IJRo+kZ
nLo5hbGOTpCG4qpTgZW+w6OcM1+le69iiOPdq0q+pOgA0s4BMPpahyf80mcQBA5d
0EVi32b/rDcfrBgrYiL+a0VgmcDuxe/9WBcvud5uZBWWdf6uEcrBHBQJf1BFWdRb
hsgzBOWuJXRiog2ZtWXoEOpD1mTFT4bunjhl1JiLx39/wr3FTVhr0ROSsxKtVywP
pdDK07b3NctmqBuLmmd0xv2tEHkMMOomabUwT1w+DdU9hNy/dfvNBqPtyInbaUyB
QkcyzKhEWnhMW0+XI/D4U4Mg1qMOCu2WZPOUnwqUUDbKx4WEL/+dAhHaMSLre5oE
rhxTxxyBo/RcuTKFMe2VcX6ilspo45uf+Mh9BpANqySJZr3LS9vWL2HolnkYoG3b
lMOq/Px/QloPsBfbTW/Q+4sZnDOOprOFCtTUZwek58mw6elxa2EeZxeTqHYN1p4u
2r9fUq4OgwzX8PXwqQhrH7p/6+oQTzPWHJsPy+AAKu4TFjaeNQiEmGoWitpOi5xW
tWG+363GPR/Er4KKSCJ4
=w/YK
-----END PGP SIGNATURE-----
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by André Warnier <aw...@ice-sa.com>.
Hassan Schroeder wrote:
> On Thu, Sep 25, 2014 at 7:18 AM, Léa Massiot <lm...@orange.fr> wrote:
>
>> I was thinking maybe about an "error-page"... (never done that before): in
>> case an exception is thrown after the response "has been committed", maybe
>> this error page could be sent to the user...
>
> Since the user's browser will still be displaying "download-file.jsp"
> after the download, why not add some JS/AJAX to the page to poll
> for a status update and display that?
>
> Just another possibility :-)
>
+1, yes, something like that.
Lea, the problem is that what you want to achieve, goes against the very logic of the
standard HTTP protocol. In HTTP, the client sends one request, and expects one response
for that request; and the server receives one request, and sens one response. The server
*can not* send a second response for that same request; and if it did, the client would
not know what to do with it.
So in your case, the client sends a request to get one file; and it expects in return that
file, not more, not less. If you try to send something else in addition to (or instead
of) the file, then the client is going to get very confused, and either see this as an
error, or it will save or display a corrupted file.
And another thing : if the server at some point notices an error while sending the
response (the file), in 99.95% of the cases this will be because the connection with the
client has been lost, and Tomcat can not write any more data on that connection. So
whatever you would try to send as an error message or page, has nowhere to go, and your
webapp would get an I/O exception.
If you really want to do something like this, then you need a "collaboration" between the
server and the client. For example, something like the above suggestion : when the client
clicks on the link to downoad the file, this does not send a request to the server
directly from the HTML page. Instead, it triggers some javascript function (AJAX-like)
which is the one that will send the request to the server, and receive the file. And
then, if at some point there is a problem in that download, the javascript function can
inform the user, by writing a message into the original browser window which is displayed
to the user, and which originated the javascript call.
But this is not as easy to do as you might think, because this javascript may not have the
permission to write to the user workstation disk, to save the received file (security).
So you may need a java applet instead, and signed, so that the user can give it the
required permissions.
So you see what you are getting into. It is certainly do-able, but do you want to go
through the effort of doing that ?
(and if you do, then search Google for "jquery").
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by Hassan Schroeder <ha...@gmail.com>.
On Thu, Sep 25, 2014 at 7:18 AM, Léa Massiot <lm...@orange.fr> wrote:
> I was thinking maybe about an "error-page"... (never done that before): in
> case an exception is thrown after the response "has been committed", maybe
> this error page could be sent to the user...
Since the user's browser will still be displaying "download-file.jsp"
after the download, why not add some JS/AJAX to the page to poll
for a status update and display that?
Just another possibility :-)
--
Hassan Schroeder ------------------------ hassan.schroeder@gmail.com
http://about.me/hassanschroeder
twitter: @hassan
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by Léa Massiot <lm...@orange.fr>.
Hello to you too,
I was thinking maybe about an "error-page"... (never done that before): in
case an exception is thrown after the response "has been committed", maybe
this error page could be sent to the user...
I don't know if it's possible... nor how to do it really.
Could it be a solution?
Best regards.
--
View this message in context: http://tomcat.10.x6.nabble.com/File-download-using-a-servlet-and-error-handling-tp5023017p5023041.html
Sent from the Tomcat - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org
Re: File download using a servlet and error handling
Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Léa,
On 9/25/14 5:48 AM, Léa Massiot wrote:
> My question is about downloading a file using a servlet and
> handling possible errors that may take place during the download
> process.
>
> 1) I have a JSP page "download-file.jsp" with a "Download file"
> button: ======================================================
> <form method="post" action="do_download_file"> [...] <input
> type="submit" name="download_file" id="download_file"
> value="Download file" /> [...] </form>
> ====================================================== When this
> button is hit by a user, the "doPost()" method of the servlet
> mapped with the action "do_download_file" is executed. It includes
> a call to the method below.
>
> 2) Everywhere on the Web one can find that type of code (for the
> file downloading):
> ====================================================== public
> boolean downloadFile(String s_fileNameAndPath, String s_fileName,
> HttpServletResponse httpServletResponse) throws IOException,
> SQLException, ClassNotFoundException, ModelException { File file =
> null; long l_fileLength = -1;
Oh, man. I hate Hungarian Notation. :/
> ServletOutputStream servletOutputStream = null; int n_bufsize =
> 4096; DataInputStream dataInputStream = null; int n_nbBytesRead =
> -1;
Why bother initializing all these local variables to default values?
Why not just declare them and then set them later? Giving them default
values doesn't gain anything and takes time during the request that
could be used to actually accomplish something. I'd remove the default
values.
> boolean b_anErrorOccurred = false;
Don't want to perform exception handling? This looks like C code...
> byte[] byteBuffer; file = new File(s_fileNameAndPath);
> l_fileLength = file.length(); if(l_fileLength <= 0) {
> b_anErrorOccurred = true; return b_anErrorOccurred; }
It's an error to have a file with zero bytes? Interesting.
> n_nbBytesRead = 0; byteBuffer = new byte[n_bufsize];
> servletOutputStream = httpServletResponse.getOutputStream();
> httpServletResponse.setContentType("text/html");
This is probably a mistake: what if it's a binary file?
> httpServletResponse.setContentLength((int) l_fileLength);
This is a mistake: l_filelength can be greater than Integer.MAX_VALUE.
Unfortunately, the Servlet API designers made this mistake long ago
and it can't be undone. Use response.setHeader("Content-Length",
String.valueOf(l_fileLength)) instead.
> httpServletResponse.setHeader("Content-Disposition", "attachment;
> filename=\"" + s_fileName + "\""); dataInputStream = new
> DataInputStream(new FileInputStream(file));
Wait, what? Why are you using a DataInputStream? A plain-old
FileInputStream will work just fine. DataInputStream is for reading
structured values from files... you just want to read bytes. Ditch the
DataInputStream.
> while((dataInputStream != null) && ((n_nbBytesRead =
> dataInputStream.read(byteBuffer)) != -1)) {
> servletOutputStream.write(byteBuffer, 0, n_nbBytesRead);
> servletOutputStream.flush();
Don't flush: buffering is your friend.
> } if(true) { throw new ModelException("To provoke an error on
> purpose."); } dataInputStream.close();
> servletOutputStream.close();
You need these close() calls in a finally block.
> return b_anErrorOccurred;
Don't return an error code; throw an exception instead.
> ====================================================== (Apart from
> the exception being thrown) this code works: it actually downloads
> the targeted file.
>
> You may have noticed that in the method above, I deliberately throw
> an exception so that I can test error handling.
>
> My problem is that, with this way of doing things, I can't tell the
> user that the download operation failed since the
> "HttpServletResponse" has already been "consumed" when the method
> returns...
The phrase you are looking for is that the response "has been
committed". That means that the headers and probably part of the
response body have already been put onto the wire and you simply can't
take them back.
> My question is: Ideally, after the download, I wish I could go back
> to the JSP "download-file.jsp" so that I can tell the user that an
> error occurred while downloading the file.
At some point, there is no way to go back. If you were
dynamically-generating the content and wanted to make sure that the
content completed successfully, you'd buffer the whole response just
to be sure. In this case, the response is already buffered (in a way
- -- it's on the disk!) so there's really nothing more you can do.
I suppose you could read the whole file into memory to ensure you
wouldn't get any read errors during the download, but then you'd need
to have huge buffers for huge files. That's a bad plan for a web
application.
> If the download was successful, I also would like to tell the user
> that everything went right...
You can't do this, either. But guess what? The user will already know
if it was successful: they will have either received Content-Length
bytes or the connection would have failed. There's no need to remind
them that the download completed successfully.
> I don't see how I can both download the file and redirect the user
> towards the "download-file.jsp" page with an appropriate message.
> Do you have an idea how I should proceed?
What you are asking is not really possible.
If you want some inspiration, read the code for the DefaultServlet.
- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1
Comment: GPGTools - http://gpgtools.org
iQIcBAEBCAAGBQJUJBPpAAoJEBzwKT+lPKRYEFEQAK0sQcHmg4WHt8rXbrRHDNZz
Hd0IcLyxJ7BtjjScx0fhcu/EOIEsGXPN2VOEIsOsapk1Y/Io5uaR/1Yo2FfSLEHk
EujSOLwkj0bx7fIRRG6IygQOSGrTWdBMtlYHcbUVbkVs2BfnM+eSw6I9GIpqiKtG
PtftRzSX2qP00K8HldoMULTQc38HRVNKKuMZE3JWmD4dSZW/uWWs7lEugrGH5ZY3
d2mjlW+mYkG7tp7ATe1Kw1qR8aaeQdHkdx369btufIYyTLYRtKzS6v8QIQ12xL+Q
nCF1QVOnbzdQr6r6ZH/Iu5xqjXStpH/lxZF89dV43FAQMCwAnW1Uiz7yBS5ancWL
zO6kVJxsvzS+fMUFy6uziByz/dH5BUuLKeOpQJ8cksJ0J2ZxDQom8LoB/UQyeLaA
qrOsHqAwQSulPW7bmh16xekqpwTqfCP8HqgC+EKQePI5a5UpJbtml+fTRIZByp7/
Gk1qM668is3ilwmpLUIrynJr3TzklkBKZ3LN4dQ0Sdshrz42F/zPT/lO3DcN3tN7
rpUrG/KrCI2/YLsKP1qS/dMzvoTx8ArS7A2ET1pkMnP7SZ1i86Vims4dtjGzRulS
h4dHt2Wl+uBm82iexyybOcvhraBXOkWFlbzRShqEQJkofDtE88iOBx/Kuz7VzJWR
hYYfeGpfPF5QJiGlXQmH
=edYK
-----END PGP SIGNATURE-----
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org