user616114
user616114

Reputation:

How to download a file from the server using Servlet

I am new to servlet technology, i need to write code to download files from the server at client side.

Can we download files diectly from the server using servlet technology?

Please provide the valuable suggestions.

Upvotes: 1

Views: 2639

Answers (1)

Nithi
Nithi

Reputation: 166

If I understand you correctly, You can download the file from HTTP servlet via response.sendRedirect() for files available in public location.

Else you need to use the response output stream to bind the file information so that it will prompt you to download for a file:

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

I gues you can handle the exceptions, of course.

Upvotes: 3

Related Questions