【问题标题】:Spring: how to download file?Spring:如何下载文件?
【发布时间】:2012-07-02 11:45:01
【问题描述】:

我想将 zip 存档从服务器保存到用户计算机。我的网页显示了有关此文件的一些信息,并有一个下载按钮。在我对按钮的控制器操作中,只需在主页上重定向,但我想从数据库中获取数据并将其保存到用户机器,路径是 由用户定义

问题是我不知道如何获得这条路径。你能举个例子吗?

【问题讨论】:

标签: java spring


【解决方案1】:

在您的控制器方法中,您可以添加此代码以获取文件下载

File file = new File("fileName");
FileInputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());

【讨论】:

    【解决方案2】:

    您不必知道如何获取路径,因为路径是由用户定义的 :) 但是如果您要查找下载路径,请检查网站的源代码以及下载按钮链接到的位置。一般可以在<form>开头看到。

    如果您只是在寻找下载文件:

    public void download(String filename, String url) {
    
        URL u;
        InputStream is = null;
        DataInputStream dis;
        String s;
    
        try{
          u = new URL(url);
    
          // throws an IOException
          is = u.openStream();
    
          dis = new DataInputStream(new BufferedInputStream(is));
          FileWriter fstream = new FileWriter(filename);
          BufferedWriter out = new BufferedWriter(fstream);
    
          while ((s = dis.readLine()) != null) {
    
              // Create file 
              out.write(s);
              //Close the output stream
              out.close();
          }
    
        }catch (Exception e){ //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    
        is.close();
    }
    

    希望这会有所帮助...

    【讨论】:

    • 感谢您的帮助,马蒂。 Dmitro 的评论有助于解决我的问题。
    【解决方案3】:

    如果您想从某个外部 URL 或 S3::: 下载

    @RequestMapping(value = "asset/{assetId}", method = RequestMethod.GET)
    public final ResponseEntity<Map<String, String>> fetch(@PathVariable("id") final String id)
        throws IOException {
    String url = "<AWS-S3-URL>";
    HttpHeaders headers = new HttpHeaders();
    headers.set("Location", url);
    
    Map<String, String> map = null;
    
    ResponseEntity<Map<String, String>> rs =
          new ResponseEntity<Map<String, String>>(map, headers, HttpStatus.MOVED_PERMANENTLY);
    
    return rs;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      相关资源
      最近更新 更多