Angular Spring 引导文件下载
Angular Spring Boot File Download
祝你阅读本文愉快!
我在这个软件设置上完成了上传功能,但我无法完成下载部分...
在这里尽可能多地挖掘,这是我到目前为止的地方。
我的代码如下所示:
服务器
@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public ResponseEntity<byte[]> getResource(@PathVariable String filename, @PathVariable Long
projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {
String fileLocation=//a location that I set, removed logic to make this shorter
File downloadFile= new File(fileLocation);
byte[] isr = Files.readAllBytes(downloadFile.toPath());
String fileName = filename;
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}
Angular 服务
downloadFile(filename: string, projectId: number): Observable<any> {
return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' });
}
Angular 组件
downloadFile(fl: FileModel) {
//calling service
this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
window.open(response.url, '_blank');
});
}
它到达服务器并返回,然后打开一个新的空白浏览器选项卡,没有其他任何事情发生。没有任何错误。
试试这个,
Spring 控制器
@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public void getResource(@PathVariable String filename, @PathVariable Long
projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {
String fileLocation=//a location that I set, removed logic to make this shorter
File downloadFile= new File(fileLocation);
byte[] isr = Files.readAllBytes(downloadFile.toPath());
ByteArrayOutputStream out = new ByteArrayOutputStream(isr.length);
out.write(isr, 0, isr.length);
response.setContentType("application/pdf");
// Use 'inline' for preview and 'attachement' for download in browser.
response.addHeader("Content-Disposition", "inline; filename=" + fileName);
OutputStream os;
try {
os = httpServletResponse.getOutputStream();
out.writeTo(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
/*HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);*/
}
Angular 服务
import { map } from "rxjs/operators";
downloadFile(filename: string, projectId: number): Observable<any> {
return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' }).pipe(map((response)=>{
return {
filename: 'yourFileName.pdf',
data: response.blob()
};
}));
}
Angular 组件
downloadFile(fl: FileModel) {
//calling service
this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
console.log(response);
var binaryData = [];
binaryData.push(response.data);
var url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.setAttribute('target', 'blank');
a.href = url;
a.download = response.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}, error => {
console.log(error);
});
}
祝你阅读本文愉快!
我在这个软件设置上完成了上传功能,但我无法完成下载部分... 在这里尽可能多地挖掘,这是我到目前为止的地方。
我的代码如下所示:
服务器
@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public ResponseEntity<byte[]> getResource(@PathVariable String filename, @PathVariable Long
projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {
String fileLocation=//a location that I set, removed logic to make this shorter
File downloadFile= new File(fileLocation);
byte[] isr = Files.readAllBytes(downloadFile.toPath());
String fileName = filename;
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}
Angular 服务
downloadFile(filename: string, projectId: number): Observable<any> {
return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' });
}
Angular 组件
downloadFile(fl: FileModel) {
//calling service
this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
window.open(response.url, '_blank');
});
}
它到达服务器并返回,然后打开一个新的空白浏览器选项卡,没有其他任何事情发生。没有任何错误。
试试这个,
Spring 控制器
@GetMapping(value = "/projects/file/download/{filename}/{projectId}")
public void getResource(@PathVariable String filename, @PathVariable Long
projectId,HttpServletResponse response) throws ResourceNotFoundException, IOException {
String fileLocation=//a location that I set, removed logic to make this shorter
File downloadFile= new File(fileLocation);
byte[] isr = Files.readAllBytes(downloadFile.toPath());
ByteArrayOutputStream out = new ByteArrayOutputStream(isr.length);
out.write(isr, 0, isr.length);
response.setContentType("application/pdf");
// Use 'inline' for preview and 'attachement' for download in browser.
response.addHeader("Content-Disposition", "inline; filename=" + fileName);
OutputStream os;
try {
os = httpServletResponse.getOutputStream();
out.writeTo(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
/*HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);*/
}
Angular 服务
import { map } from "rxjs/operators";
downloadFile(filename: string, projectId: number): Observable<any> {
return this.http.get(`${this.baseUrl}/file/download/` + filename + '/' + projectId, { responseType: 'blob' }).pipe(map((response)=>{
return {
filename: 'yourFileName.pdf',
data: response.blob()
};
}));
}
Angular 组件
downloadFile(fl: FileModel) {
//calling service
this.projectSerivce.downloadFile(fl.fileName, this.id).subscribe(response => {
console.log(response);
var binaryData = [];
binaryData.push(response.data);
var url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.setAttribute('target', 'blank');
a.href = url;
a.download = response.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}, error => {
console.log(error);
});
}