简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM