-1

I am writing a Java server program. Currently I'm using a DataOutputStream to output files to the requesting client or browser. I want the files to be sent to a particular directory on the client's side and not just to the browser (I do not want to write a client program to handle this issue). How do I make the server program write the file to a particular directory on the client's side?

Thanks in advance

Priidu Neemre
  • 2,813
  • 2
  • 39
  • 40
Imprfectluck
  • 654
  • 6
  • 26

1 Answers1

3

Server doesn't know anything about client and neither is this a good idea to allow server to write files or anything on the client directories as it's an Http Security concerns and it won't allow servers to write viruses, changing properties etc on the user's machines who are visiting their web page.

So, what you can do is, client can send a request to server and server will write file on the client (e.g. browser AND not the directory) with sending back some mime-type. There are few mime-types which now a days, browsers can handle and show to the client from within the browser. Client can then download it or discard it as per his/her own choice to any directory on his/her machine.

Here is a bit of code you can write on server side to achieve what I said above:

        OutputStream out = response.getOutputStream();
        File file = new File(path_to_a_file);
        response.setContentType(file_content_type);
        response.setHeader("Content-disposition","attachment; filename="+FILE_NAME);
        FileInputStream inputStream = new FileInputStream(FILE);
        //Read bytes and write until finished
SSC
  • 2,956
  • 3
  • 27
  • 43
  • I was thinking about the same lines. But did not know about the content disposition header. You sir have my deepest gratitude :D.. Thanks a lot !! (It works fine BTW :) ) – Imprfectluck Apr 13 '15 at 19:52
  • Is there a way to downlad the file and still view it in the browser? – Imprfectluck Apr 17 '15 at 14:08
  • Your browser needs to have that extension available for viewing. Forexample, when you open pdf's, they open in the browser (but eventually they download on the client side but just viewed in the browser) – SSC Apr 17 '15 at 14:10
  • Ah i see . Got it. I keep thinking that the server should do all the stuff. Thanks for the help :) – Imprfectluck Apr 23 '15 at 13:08