开发者

After form-submit, download file

Im using struts2 and also servlets. (Due to a 3rd party ajax thing that ships with servlets).

One of my forms is posting to a servlet. (Name "/exclude/new.srl") I've set struts2 up to ignore all requests to the "exclude" namespace. So the request is reaching the servlet just fine.

The servlet does its job, and then goes on to do the following before ending:

response.getOutputStream().print("'OK'");
response.getOutputStream().close();

Now i dont know the 3rd party software in detail, so im not exactly sure, but i think the OK statement tells my 3rd party ajax-solution to close the form and refresh some contents of the page.

This all works fine.

Now however i am trying to add a new bit to this. I would like send a file to the user. In other words, when the form is submitted, everything that used to happen should still happen, but also the user should be asked to save or open a file.

So I have created a struts2 action that will return the file, no problem. But how can i program the servlet to push this file to the user AND ALSO return response OK? I do not need to use the struts2 action to push the file, if it can be done from within the servlet that is perfectly acceptable.

开发者_C百科

Anyone?


You can send the file

// Set the headers.
res.setContentType("application/x-download");
res.setHeader("Content-Disposition", "attachment; filename=" + filename);

// Send the file.
OutputStream out = res.getOutputStream();
File file = new File(yourPath);
response.setContentLength((int) file.length());

BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
int readBytes = 0;
while ((readBytes = buf.read()) != -1)
    stream.write(readBytes);
buf.close();
stream.close();

But how can i program the servlet to push this file to the user AND ALSO return response OK?

This I don't think is possible. The response from a servlet has a tyle, denoted by the content-type. If you set it to a download, then you cannot send a normal response, meaning you cannot send the "OK".


You will probably have to setup your unmentioned 3rd party ajax-solution to forward to the file action/servlet URL on form submission success (ie redirect to file download after form was submitted ok).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜