Issue
How should I implement simple file download servlet?
The idea is that with the GET request index.jsp?filename=file.txt
, the user can download for example. file.txt
from the file servlet and the file servlet would upload that file to user.
I am able to get the file, but how can I implement file download?
Solution
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.
Answered By - ChssPly76
Answer Checked By - Pedro (JavaFixing Volunteer)