@Controller @RequestMapping("/download") public class DownloadController {
@Autowired
private FileStorageService fileStorageService;
@GetMapping("/{fileName:.+}")
public ResponseEntity downloadFile(@PathVariable String fileName) {
Resource resource = fileStorageService.loadFileAsResource(fileName);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
constructor(private http: HttpClient) { }
downloadFile() { const fileName = 'example.pdf'; this.http.get('/download/' + fileName, { responseType: 'blob' }) .subscribe(res => { const url = URL.createObjectURL(res); const a = document.createElement('a'); document.body.appendChild(a); a.setAttribute('style', 'display: none'); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); a.remove(); // remove the element }, error => { console.log('Error downloading the file.'); }); }
确保文件类型和文件扩展名匹配。例如,在上面的示例中,我们将HTTP响应类型设置为“blob”。这将返回一个二进制流对象,而不是文本或Json对象。在响应结束时,我们将二进制流对象转换为URL,然后使用生成的URL创建新的“a”元素,将其附加到DOM树中,并模拟单击该元素以启动文件下载。注意,您还应该删除“a”元素并释放URL资源。
确保文件名不包含任何非法字符或路径分隔符。在我们的示例中,我们使用“fileName”参数来创建下载文件的新文件名。这种方法可以有效防止文件路径遍历(例如“/../”)攻击。