Home > Back-end >  How to provide files for download that might change (but not path) in Controller?
How to provide files for download that might change (but not path) in Controller?

Time:12-15

This is the controller i have so far created:

@Controller
public class DownloadController
{
    @GetMapping(path = "/download")
    public ResponseEntity<Resource> download(
            @RequestParam(value = "file", required = true, defaultValue = "") String param)
    {
        if (!param.equals("win") && !param.equals("linux") && !param.equals("mac"))
        {
            return null;
        }
        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="   param   ".zip");
        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
        header.add("Pragma", "no-cache");
        header.add("Expires", "0");
        File file = new File("/dl/"   param   ".zip");
        System.out.println("File exists: "   file.isFile()   "path: "   file.getPath()); // <- returns false and path: \dl\{param}.zip
        InputStreamResource isr;
        try
        {
            isr = new InputStreamResource(new FileInputStream(new File("/dl/"   param   ".zip")));
            return ResponseEntity.ok().headers(header).contentLength(file.length())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM).body(isr);
        } catch (FileNotFoundException e)
        {
            return null;
        }
    }
}

Structure:

structure

I'd like to provide files for download, which are in a folder as shown in structure.

I am doing it this way, because files provided for download might change and I do not want to re-deploy application. However files are not found.

CodePudding user response:

Use below code for fetch resource files from your storage

private final Path root = Paths.get("dl");

public Resource load(String filename) {
   try {
  
      Path file = root.resolve(filename);

      Resource resource = new UrlResource(file.toUri());
      if (resource.exists() || resource.isReadable()) {
    
          return resource;
  
      } else {
    
          throw new RuntimeException("Could not read the file!");
  
      }

   } catch ( MalformedURLException e) {
  
       throw new RuntimeException("Error: "   e.getMessage());

   }
}

Also use this code to send file through the rest call. (Implement in the controller)

 @GetMapping("/fetch/{filename:. }")

 @ResponseBody

 public ResponseEntity<Resource> getFile( @PathVariable String filename )
{
    
     Resource file = load( filename );
 
     return ResponseEntity.ok()
            
      .header( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""   file.getFilename()   "\"" ).body( file );

}
  • Related