繁体   English   中英

通过浏览器从servlet下载文件

[英]Download file from servlet through browser

我应该通过浏览器从服务器下载一个csv文件。 我尝试使用以下代码的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"); 

}

但是该程序没有下载Download文件夹中的任何文件,该程序让我在浏览器中看到csv内容。 我需要在浏览器的下载文件夹中有VR.csv。

您没有设定回应! 如果要下载特定文件,则需要在响应中指定要下载的类型和特定文件的路径。

         response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=yourFileName.csv");

除了先前的答案,您的方法还应该具有返回类型,就像您使用Spring Framework一样,它应该具有ModelAndView,如下所示

公共ModelAndView writeFile(字符串文件名,字符串内容,HttpServletResponse响应)引发IOException {}

暂无
暂无

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

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