2

I want to save zip archive from server to user computer. I have web page that shows some information about this file and has a download button. In my controller action on button simply redirect on homepage but I want to get data from database and save it to user machine with path is defined by user

The issue is that I don't know how I can get this path. Could you give me an example how I can do that?

Winte Winte
  • 753
  • 5
  • 11
  • 24

3 Answers3

1

In your controller method you can add this code to get file download

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());
Abhishek bhutra
  • 1,400
  • 1
  • 11
  • 29
0

You don't have to know how to get the path, because the path is defined by the user :) But if your looking for the download path, check the source code of the website and where the download button links to. Usually you can see it in the beginning of the <form>.

If you are just looking for download a file:

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();
}

Hope this helps...

Mualig
  • 1,444
  • 1
  • 19
  • 42
marty bourque
  • 734
  • 4
  • 7
  • 20
0

If you want to download from some external URL or from 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;

}

y-c
  • 1
  • 1