如果你同时使用 Web API 和 Angular 2-4,这里是一个很好的例子。
网络接口:
public HttpResponseMessage File(string fileName, string mimeType, byte[] content)
{
//create stream
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new ByteArrayContent(content);
httpResponseMessage.Content.Headers.Add("x-filename", fileName);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentLength = content.Length;
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
角度:
//get Blob data from file and open it new tab
openPdfToNewTab(url: string) {
Observable.create(observer => {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.getFullPathUrl(url), true);
xhr.setRequestHeader('Content-type', 'application/pdf');
xhr.responseType = 'blob';
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var contentType = 'application/pdf';
var blob = new Blob([xhr.response], { type: contentType });
observer.next(blob);
observer.complete();
} else {
observer.error(xhr.response);
}
}
}
xhr.send();
}).subscribe(data => {
var blob = new Blob([(<any>data)], { type: 'application/pdf' });
var url = window.URL.createObjectURL(blob);
window.open(url);
},
err => {
},
() => { });
};
用法:
API:
[HttpGet]
public HttpResponseMessage GetMainPdf(int taskId)//, string token
{
//your code here
var fileData = GetFile(); //some code here
// return file
return File($"{fileData.FileName}", fileData.MimeType, fileData.Content);
}
角度:
//you can call this function on click
getMainPdf() {
return this.openPdfToNewTab(YOUR-API-URL); //url for download file
}