簡體   English   中英

如何在 Controller 中提供可能更改(但不是路徑)的文件以供下載?

[英]How to provide files for download that might change (but not path) in Controller?

這是迄今為止我創建的 controller:

@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;
        }
    }
}

結構:

結構體

我想提供文件供下載,這些文件位於結構中所示的文件夾中。

我這樣做是因為提供下載的文件可能會更改,我不想重新部署應用程序。 但是找不到文件。

使用以下代碼從存儲中獲取資源文件

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

   }
}

也可以使用此代碼通過 rest 調用發送文件。 (在控制器中實現)

 @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 );

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM