我正在尝试从服务器下载文件,但该文件未显示其原始内容,而是显示 [object Object]。
WEB API核心
[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;
}
);
}
精慕HU
相关分类