1

I should download a csv file from the server through browser. I try with servlet with following code

private void writeFile(String filename, String content, HttpServletResponse response) throws IOException {


    String filename="VR.csv";
     try {
     File file = new File(filename);


     FileWriter fw = new FileWriter(file);
     BufferedWriter bw = new BufferedWriter(fw);
     bw.write(content);
     bw.flush();
     bw.close();
     }
     catch(IOException e) {
     e.printStackTrace();
     }


     // This should send the file to browser
     ServletOutputStream out = response.getOutputStream();

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



    System.out.println("done"); 

}

But the program doesn't download any file in Download folder, program let me see in the browser the csv content. I need to have the VR.csv in the download folder of the browser.

hadi.mansouri
  • 828
  • 11
  • 25
Hydronit
  • 29
  • 1
  • 5
  • You need to set some attributes of `response` object (like `Content-Disposition` header and `contentType`) for that. Please check answers to this question: https://stackoverflow.com/questions/1442893/implementing-a-simple-file-download-servlet – Ivan Apr 03 '18 at 15:58

2 Answers2

0

You are not setting your response! If you want to download an specific file you need to specific in the response what type are you downloading and the path of the specific file.

         response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=yourFileName.csv");
Gatusko
  • 2,503
  • 1
  • 17
  • 25
0

In addition to previous answer, your method should have return type, like it should have ModelAndView if you use Spring Framework as follows

public ModelAndView writeFile(String filename, String content, HttpServletResponse response) throws IOException {}

Pandian
  • 131
  • 3
  • 15