gpt4 book ai didi

java - 我如何实现从API下载文件

转载 作者:行者123 更新时间:2023-12-01 16:18:43 25 4
gpt4 key购买 nike

我无法从我实现的 Angular 从我的 friend 服务java代码下载文件,并且我不知道如何实现从 Angular 下载文件,请帮助我

我的 Angular 代码

    private _download$ = new Subject<void>();
**this._download$.pipe(switchMap(()=>this._downloadFile())).subscribe(resultBlob =>{
console.log("Success to Next ")
this.loadFile(resultBlob)
},(exception:any)=>{
console.log("exception: ",exception)
},()=>{
console.log("Complete: ")
})
}**

**private _downloadFile(){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/octet-stream',
responseType : 'blob',
Accept : 'application/octet-stream',
observe : 'response'
})
};**
return this.http.get<Blob>('/col-corecollection-service/exclusion/download-file/'+this.exclusionCode,httpOptions)
}
private download(){
this._download$.next();
}
loadFile(data: any) {
var blob = new Blob([data], {type: 'application/octet-stream'});
var downloadURL = window.URL.createObjectURL(data);
window.open(downloadURL);
}**

And I have code service that my friend implement like this

@GetMapping("/exclusion/download-file/{exclCode}")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resource> exclusionDownloadFile(
@Size(min = 1, max = 50)
@PathVariable String exclCode
) {
if (!this.exclusionService.existsExclusionById(exclCode)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Exclusion code " + exclCode + " not found.", null);
}
SearchExclFilenameExclBlobByIdResponse downloadFile = this.exclusionService.searchExclFilenameExclBlob(exclCode);
byte[] fileData = downloadFile.getExclBlob();
Resource resource = new InputStreamResource(new ByteArrayInputStream(fileData));
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadFile.getExclFilename() + "\"")
.body(resource);
}

当我点击下载按钮时无法下载文件给我,请帮忙

最佳答案

尝试在 header 外部传递responseType

从 header 中删除响应类型:

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/octet-stream',
Accept : 'application/octet-stream',
observe : 'response'
})
};

以下是用于在 header 外部传递responseType 的更新代码:

return this.http.get<Blob>('/col-corecollection-service/exclusion/download-file/'+this.exclusionCode,{headers: httpOptions.headers, responseType: 'blob'})

然后,如果您想下载,请使用 fileSaver:

var file = new Blob([data], { type: "application/octet-stream" });
this.fileSaverService.save(file);

关于java - 我如何实现从API下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62332045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com