angular - 使用 Angular 6 从 ASP.NET Web API 方法下载文件
问题描述
我想使用 Angular6 和 Web API 下载有关 URL 点击事件的 PDF 和 doc 文件。
组件.ts
download(ID: number) {
this._Services.download_test(ID).subscribe(res => {
const data = new Blob([res], { type: 'text/plain;charset=utf-8' });
saveAs(data, 'text.docx');
console.log(data);
});
}
服务.ts
public download_test(Id: number): Observable<Blob> {
const headers = new HttpHeaders().set('content-type', 'multipart/form-data');
return this.http.get(_baseUrl + 'GetFileDetail' + '?id=' + Id,
{ headers, responseType: 'blob' }).pipe(
map((res: Response) => {
console.log(res.headers);
console.log(res.blob());
return new Blob([res.blob()], { type: 'application/octet-stream' });
}
));
}
API
[HttpGet]
public HttpResponseMessage GetFileDetail(int id)
{
//Create HTTP Response.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
string fileName;
//Fetch the File data from Database.
Dictionary<string, object> rec;
DbConnection conn = CommonFunction.GetDBConnection();
conn.Open();
string qrystr = "SELECT FileName,FileType,FileContent "
+ " FROM tFileData "
+ " where ID = " + id;
rec = CommonFunction.GetSingleRecord(qrystr, conn);
if (rec.Count != 0)
{
Byte[] data = (Byte[])rec["FileContent"];
string Type = rec["FileType"].ToString();
fileName = rec["FileName"].ToString();
MemoryStream ms = new MemoryStream(data);
//Set the Response Content.
response.Content = new StreamContent(ms);
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentLength = data.LongLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
return response;
}
这段代码对我不起作用。它抛出错误:
ERROR TypeError: res.blob is not a function
解决方案
我修改了我的service.ts文件如下:
public download_test(Id: number): Observable<Blob> {
const headers = new HttpHeaders().set('content-type', 'multipart/form-data');
return this.http.get(_baseUrl + 'GetFileDetail' + '?id=' + Id,
{ headers, responseType: 'blob' });
}
和components.ts文件:
download(ID: string) {
this._jobServices.download_test(ID).subscribe(res => {
const data = new Blob([res], { type: 'application/pdf' });
saveAs(data);
console.log(data);
});
}
它正在工作。谢谢!