简体   繁体   English

通过浏览器从servlet下载文件

[英]Download file from servlet through browser

I should download a csv file from the server through browser. 我应该通过浏览器从服务器下载一个csv文件。 I try with servlet with following code 我尝试使用以下代码的servlet

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. 但是该程序没有下载Download文件夹中的任何文件,该程序让我在浏览器中看到csv内容。 I need to have the VR.csv in the download folder of the browser. 我需要在浏览器的下载文件夹中有VR.csv。

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");

In addition to previous answer, your method should have return type, like it should have ModelAndView if you use Spring Framework as follows 除了先前的答案,您的方法还应该具有返回类型,就像您使用Spring Framework一样,它应该具有ModelAndView,如下所示

public ModelAndView writeFile(String filename, String content, HttpServletResponse response) throws IOException {} 公共ModelAndView writeFile(字符串文件名,字符串内容,HttpServletResponse响应)引发IOException {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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