gpt4 book ai didi

java - Angular 2 : download file from Rest webservice

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:50 24 4
gpt4 key购买 nike

我有这个 JAVA Web 服务用于下载文件:

@Path("test")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public javax.ws.rs.core.Response downloadFile() {
File folder = new File("Myfolder");
File file = new File(folder.getAbsolutePath() + "/" + "myFile.txt");

return javax.ws.rs.core.Response.ok((Object) file).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, HEAD, OPTIONS")
.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type, X-Codingpedia")
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"").build();
}

我需要从我的 angular2 应用程序下载它。我已经实现了这项服务:

download():Observable<Response> {

let params = new URLSearchParams();
let requestOptions = new RequestOptions({
headers: this.getHeaders2(),
search: params
});

requestOptions.method=RequestMethod.Get;
requestOptions.url ="myUrl";
requestOptions.responseType = ResponseContentType.Blob;
let request = new Request(requestOptions);
return this.http.request(request);
}

private getHeaders2() {
let headers = new Headers();
headers.append('Content-Type', 'application/octet-stream');
headers.append('responseType', 'arrayBuffer');
return headers;
}

这就是我在组件上调用服务的方式:

this.services.download().subscribe(
response => {
let file = response.blob();
console.log(file.size + " bytes file downloaded. File type: ", file.type);
var url =window.URL.createObjectURL(file);
window.open(url);
},
error => console.log(JSON.stringify(error))
);

但我收到错误:

"Error: The request body isn't either a blob or an array buffer\n

出了什么问题?

最佳答案

尝试这样:

this.services.download().subscribe(response => {

// create a new Blob by defining its content-type
let file = new Blob([response.blob()], { type: 'application/octet-stream' });

console.log(file.size + " bytes file downloaded. File type: ", file.type);
var url =window.URL.createObjectURL(file);
window.open(url);
},
error => console.log(JSON.stringify(error)

);

关于java - Angular 2 : download file from Rest webservice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45162787/

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