Angular 2从Nodejs保存文件



我在NodeJS中剪下了一些片段,试图从我的服务器上下载。

router.post("/download", function(req, res, next) {
console.log(req);
filepath = path.join(__dirname, "/files") + "/" + req.body.filename;
console.log(filepath);
res.sendFile(filepath);
});

这是我的Angular 2代码:组件.ts

download(index) {
var filename = this.attachmentList[index].uploadname;
this._uploadService
.downloadFile(filename)
.subscribe(data => saveAs(data, filename), error => console.log(error));
}

服务.ts

export class UploadService {
constructor(private http: HttpClient, private loginService: LoginService) {}
httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
responseType: "blob"
})
};
downloadFile(file: string): Observable<Blob> {
var body = { filename: file };
console.log(body);
return this.http.post<Blob>(
"http://localhost:8080/download",
body,
this.httpOptions
);
}

在我的HTML响应中,我将文件正确记录到浏览器的网络检查工具中。然而,Angular正试图将响应解析为JSON对象,这显然不起作用,因为响应是一个blob。

我得到的错误是:

JSON.parse((位置0处的JSON中出现意外的令牌%在XMLHttpRequest.onLoad angular 2

有人对此有解决方案吗?

提前感谢!

尝试以下http选项:

{
responseType: 'blob',
observe:'response'
}

然后,您将得到一个类型为HttpResponse<Blob>的响应,因此在服务中执行data.body操作将为您提供可以传递给saveAs的blob。

你可以在这里找到更多关于观察的信息:

https://angular.io/guide/http#reading-全响应

我解决了这个问题,在服务代码中,我删除了帖子后面的,因为它迫使我返回一个二进制文件,而不是JSON。现在代码是这样的:

downloadFile(file: string): Observable<Blob> {
var body = { filename: file };
console.log(body);
return this.http.post<Blob>(
"http://localhost:8080/download",
body,
this.httpOptions
);
}

谢谢大家。

最新更新