0

I have a website using Java Servlets.

On my main html page I have a link that should start the download of a file from the server.

I have this in my html:

<a href="/download(file_id=1)">Download</a>

And this in my download Controller:

Integer file_id = Integer.valueOf(request.getParameter("file_id"));
try{
   if(file_id == 1){
      File f = new File("/home/me/myfile.mp3");
      // TODO
   }
}catch(Exception){}

And I'm stuck here. How can I continue so that the client will receive the file and start downloading it?

So far all I could find in search engines are php tutorials, which I'm not using.

Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71

1 Answers1

1

I have found some examples that should give you an idea of how to do this.

java-code-to-download-a-file-from-server This is from SO.

example-of-downloading-file-from-the-server-in-servlet

This a more complex example: servlet-upload-file-and-download-file-example

In all the examples you will find that some sort of stream class is used with a response object.

Furthermore I think your code should look more like:

<a href="/download?file_id=1">Download</a>

Use an extension if needed after 'download'. If you are going to use the case statement to find the right file it would also be better to use a GUID to find the file, but if security is no concern why not use the proper file name?

BTW I used the following words to search on google:

java download file from server example html page

with the last two word only added later to see if I could find a better example, but it mainly returned the same results.

I don't have a Java development environment so I can't create a working example for you. You should be able to work this out.

Community
  • 1
  • 1
Sigur
  • 317
  • 1
  • 3
  • 12