我试图从服务器下载文件,但文件没有显示原始内容,而是显示了 [object Object]。
WEB API CORE
WEB API CORE
[Authorize(AuthenticationSchemes = "Bearer")]
[HttpGet]
public HttpResponseMessage DownloadContractFile(string fileName)
{
string contentRootPath = _hostingEnvironment.ContentRootPath;
var folderName = Path.Combine(contentRootPath, FileHandler.ContractFilePath, Convert.ToInt32(User.Identity.Name).ToString());
var path = Path.Combine(folderName, fileName);
var memory = new MemoryStream();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var stream = new FileStream(path, FileMode.Open))
{
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(FileHandler.GetContentType(path)); // Text file
result.Content.Headers.ContentLength = stream.Length;
return result;
}
}
Angular 代码:服务方法
downloadContractFile(fileName: string) {
const obj: any = { fileName: fileName };
const httpParams: HttpParamsOptions = { fromObject: obj } as HttpParamsOptions;
const httpOptions = {
params: new HttpParams(httpParams),
headers: new HttpHeaders({
'Content-Type': 'application/octet-stream',
'Authorization': 'Bearer ' + this.jwt.getToken
})
};
return this.http.get<Array<any>>(`${this.settings.getApiSettings('uri')}/api/contract/DownloadContractFile`, httpOptions).map( /// <<<=== use `map` here
(response) => {
if (response["status"] == 401) {
this.jwt.redirectToLogin();
}
else if (response["status"] < 200 || response["status"] >= 300) {
throw new Error('This request has failed ' + response["status"]);
}
let data = response;
return data;
}
);
}
Component.ts
downloadFile(fileName) {
this.js.checkTokenValid().subscribe(res => {
if (res == null)
this.js.redirectToLogin();
else {
this.conc.downloadContractFile(fileName).subscribe(respData => {
console.log(respData);
this.type = respData.content["headers"][1]["value"][0];
this.downFile(respData.content, this.type, fileName);
}, error => {
});
}
});
}
downFile(data: any, type: string, fileName: string) {
var blob = new Blob([data], { type: type });
var url = window.URL.createObjectURL(blob);
saveAs(blob, fileName);
//var fileURL = URL.createObjectURL(res);
//window.open(fileURL); // if you want to open it in new tab
}
Component.html
<a href="javascript:void(0)" (click)="downloadFile(item.fileName);">download file</a>
收到响应
收到文件内容