views:

344

answers:

3

How should I implement very basic file download servlet? Idea is that with GET request index.jsp?filename=file.txt user could download for example file.txt from file servlet and file servlet would upload that file to user. I can get file, but how should I implement file download?

A: 

You can use Struts Framework to implement it.

Peter Lee
That is not an answer. Care to elaborate?
ChssPly76
He's probably referring to Commons FileUpload support in Struts and DownloadAction. @ChssPly76, your answer is a good generic answer given the information provided in the question.
John Doe
+7  A: 

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

If it's not, you'll need to manually copy it to response output stream:

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

You'll need to handle the appropriate exceptions, of course.

ChssPly76
+1  A: 

The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.

You can easily achieve it through:

HttpServletResponse.sendRedirect()
Winston Chen