Angular前端和Spring后端文件下载不起作用或文件损坏
创始人
2024-10-29 02:00:40
0
  1. 确保后端正确配置文件下载功能。以下示例是Spring MVC中的文件下载控制器:

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

}

  1. 在Angular中使用HttpClient对后端控制器进行HTTP GET请求。以下是一个使用Angular HttpClient进行文件下载的示例:

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.'); }); }

  1. 确保文件类型和文件扩展名匹配。例如,在上面的示例中,我们将HTTP响应类型设置为“blob”。这将返回一个二进制流对象,而不是文本或Json对象。在响应结束时,我们将二进制流对象转换为URL,然后使用生成的URL创建新的“a”元素,将其附加到DOM树中,并模拟单击该元素以启动文件下载。注意,您还应该删除“a”元素并释放URL资源。

  2. 确保文件名不包含任何非法字符或路径分隔符。在我们的示例中,我们使用“fileName”参数来创建下载文件的新文件名。这种方法可以有效防止文件路径遍历(例如“/../”)攻击。

相关内容

热门资讯

aapoker辅助实际测试(a... aapoker辅助实际测试(aa poker)aapoker有网页版吗(辅助挂)新2025版(本来真...
黑科技代打(wePOKE)黑科... 黑科技代打(wePOKE)黑科技透明挂辅助方法(透视)透明教程(好像是真的有挂)1、金币登录送、破产...
aa扑克发牌机制(aa pok... aa扑克发牌机制(aa poker)aapoker用外挂会被封号吗(辅助挂)2025教程(一直有挂)...
黑科技线上(wePokE)黑科... 黑科技线上(wePokE)黑科技透明挂辅助插件(透视)透明挂教程(竟然是有挂);1、wePokE系统...
wepoke黑科技功能演示(w... wepoke黑科技功能演示(wepoKe)wepower提高中牌率(黑科技)靠谱教程(真是真的有挂)...
黑科技有挂(德州)外挂辅助软件... 黑科技有挂(德州)外挂辅助软件(透视)黑科技教程(其实存在有挂)1、让任何用户在无需德州AI插件第三...
aapoker透明挂辅助器(A... aapoker透明挂辅助器(AAPOkER)aapoker安卓怎么下载(辅助挂)新2025版(总是是...
黑科技科技(Aapoker)外... 黑科技科技(Aapoker)外挂透视辅助神器(透视)玩家教你(原来存在有挂);1、Aapoker透视...
wepoke有插件吗!wepo... 1、wepoke有插件吗!wepoke辅助透,wepoke辅助挂,辅助教程(有挂方法)2、进入游戏-...
黑科技挂(wePoKe)黑科技... 黑科技挂(wePoKe)黑科技透明挂辅助软件(透视)力荐教程(真是存在有挂)1、wePoKe透视辅助...