Spring:如何下载文件?

时间:2012-07-02 11:45:02

标签: java spring

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

问题在于我不知道如何才能获得这条道路。你能举个例子说明我怎么做的吗?

3 个答案:

答案 0 :(得分: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());

答案 1 :(得分:0)

您不必知道如何获取路径,因为路径是由用户定义的:)但是如果您要查找下载路径,请检查网站的源代码以及下载按钮链接的位置。通常,您可以在<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();
}

希望这会有所帮助......

答案 2 :(得分:0)

如果您想从某些外部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;

}