這是我迄今為止創建的控制器:
@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;
}
}
}
結構:

我想提供可供下載的檔案,它們位于結構中所示的檔案夾中。
我這樣做是因為提供下載的檔案可能會改變,我不想重新部署應用程式。但是找不到檔案。
uj5u.com熱心網友回復:
使用以下代碼從您的存盤中獲取資源檔案
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 );?
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/381714.html
