问题描述
需要下载动态文件,该文件是根据客户端api的类型从其返回的.这就是我所拥有的
Need to download dynamic files which is returned from the api in the client side based on its type. This is what i have
我的 api控制器看起来像这样
public async Task<IActionResult> GetFile(int id)
{
IBaseResult<UserDetails> result = await _Bo.GetUSerDetails(id);
//result will have content likes
//1. FileName//fileaname.{extention}
//2. FileType//eg.application/pdf or application/doc
//3. FileContent//byte[]
if (result.Data != null)
{
response.Success = result.success;
response.Data = result.Data;
return Ok(response);
}
}
.ts 文件如下所示:
data.service.ts
getResume(methodName: string, id :string): Observable<any> {
let httpOptions = this.getAuthoriseHeader();
return this.http.get(environment.baseApiUrl + methodName + id, { headers: httpOptions, observe: 'response', responseType: 'blob' });
}
view.component.ts
this.dataservice.getResume(method, id).subscribe(result => {
var resume = result["data"];
var fileName = resume.resumeName;
var fileType = resume.resumeType;
const file = new Blob([resume.resume], { type: fileType });//Is this correct or do i need to use 'application/octet-stream' here?
saveAs(file, fileName);
});
正在下载上面的实现文件,但是当我尝试打开文件时,下面显示了
With above implementation file is downloading but when i try to open the file, below is showng
我的响应对象是
更新:
我在.ts文件中尝试过
I tried this in my .ts file
var fileName = resume.resumeName;var fileType = resume.resumeType;//var byteArray = new Uint8Array(resume.resume);
var fileName = resume.resumeName;var fileType = resume.resumeType;//var byteArray = new Uint8Array(resume.resume);
const file = new Blob([resume.resume], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(file));
let a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = this.fileUrl;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(this.fileUrl);
a.remove();
正在下载文件,但出现失败-没有文件错误
File is downloading with Failed - No file error
推荐答案
最后,我找到了解决方案,现在可以正常工作了.我怀疑这是将我的Blob数据转换为保存问题.
Finally i found solution and its working fine now. As i suspected it was issue with converting my blob data to save.
const binaryString = window.atob(resume.resume); // Comment this if not using base64
const bytes = new Uint8Array(binaryString.length);
return bytes.map((byte, i) => binaryString.charCodeAt(i));
然后我用
const blob = new Blob([body]);
//rest of the code is same as posted question
本文确实为解决方案提供了帮助
This article really helped with solution
https://medium.com/@riccardopolacci/download-file-in-javascript-from-bytea-6a0c5bb3bbdb
这篇关于从API读取文件及其属性,然后在Angular Client中下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!