我已经开发了一个应用程序,我有一个方法从我的应用程序下载文件。当我通过api运行此方法时,该文件将被成功下载,但是如果我按下应用程序中要下载的按钮,这就无法工作,调试就可以了。他们的日志是一样的:
通过http://localhost:9060/api/ticket-download登录
2019-04-12 19:20:51.971 DEBUG 940 --- [ XNIO-6 task-6] c.g.aop.logging.LoggingAspect : Enter: com.app.web.rest.TicketResource.downloadFile() with argument[s] = []
2019-04-12 19:20:51.973 DEBUG 940 --- [ XNIO-6 task-6] c.g.aop.logging.LoggingAspect : Exit: com.app.web.rest.TicketResource.downloadFile() with result = <200 OK,Byte array resource [resource loaded from byte array],{Content-Disposition=[attachment; filename=ticket.pdf], Cache-Control=[no-cache, no-store, must-revalidate], Pragma=[no-cache], Expires=[0], Content-Length=[92672], Content-Type=[application/pdf]}>日志通过应用程序
2019-04-12 19:23:43.341 DEBUG 940 --- [ XNIO-6 task-7] c.g.aop.logging.LoggingAspect : Enter: com.app.web.rest.TicketResource.downloadFile() with argument[s] = []
2019-04-12 19:23:43.343 DEBUG 940 --- [ XNIO-6 task-7] c.g.aop.logging.LoggingAspect : Exit: com.app.web.rest.TicketResource.downloadFile() with result = <200 OK,Byte array resource [resource loaded from byte array],{Content-Disposition=[attachment; filename=ticket.pdf], Cache-Control=[no-cache, no-store, must-revalidate], Pragma=[no-cache], Expires=[0], Content-Length=[92672], Content-Type=[application/pdf]}>TicketResource.java
@RestController
@RequestMapping("/api")
public class TicketResource {
@GetMapping("/ticket-download")
public ResponseEntity<Resource> downloadFile() {
File file = new File("D:/Tickets/ticket.pdf");
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=ticket.pdf");
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource;
try {
resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok().headers(header).contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf")).body(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}我希望通过单击我的应用程序中的“下载”按钮,该文件将被正确下载。
发布于 2019-04-16 11:24:06
您必须修改service.component.ts和ticket.component.ts以处理资源响应。我建议您使用FileSaver库。下面是Spring的角下载文件示例,它可以帮助您完成必须做的事情:http://roufid.com/angular-download-file-spring-boot/
发布于 2019-04-12 17:59:21
我对Spring非常陌生,但您需要为下载控制器附加代码,而不是下载实际发生的代码。
文件是实际创建的吗?
路径存在(路径的所有目录都存在)?
编辑:我还没有意识到他谈论的是一个web应用程序,而不是swing或javafx,所以以前的代码是无用的。抱歉的。
也许这个函数是不完整的,试试这样的东西:
downloadFile(): Observable<any> {
return this.http
.get(SERVER_API_URL + 'api/ticket-download')
.subscribe((data) => {
this.blob = new Blob([data], {type: 'application/pdf'});
var downloadURL = window.URL.createObjectURL(this.blob);
window.open(downloadUrl);
});或者使用FileSaver库。
https://stackoverflow.com/questions/55656953
复制相似问题