【发布时间】:2018-09-08 02:23:44
【问题描述】:
我想使用 Angular6 和 Web API 下载有关 URL 点击事件的 PDF 和 doc 文件。
Component.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);
});
}
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' }).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
【问题讨论】:
-
console.log(res.headers);显示什么?我假设它是undefined... -
没有必要在
download方法中做map,你已经告诉 angular,responseType 是 'blob'