我有这个JAVA webservice下载文件:
@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
出了什么问题?
答案 0 :(得分:0)
以这种方式尝试:
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)
);