在我的Angular JS项目中,我有一个<a>
锚标记,当单击它时会GET
向返回文件的WebAPI方法发出HTTP 请求.
现在,我希望在请求成功后将文件下载到用户.我怎么做?
锚标记:
<a href="#" ng-click="getthefile()">Download img</a>
Run Code Online (Sandbox Code Playgroud)
AngularJS:
$scope.getthefile = function () {
$http({
method: 'GET',
cache: false,
url: $scope.appPath + 'CourseRegConfirm/getfile',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function (data, status) {
console.log(data); // Displays text data if the file is a text file, binary if it's an image
// What should I write here to download the file I receive from the WebAPI method?
}).error(function (data, status) {
// ...
});
}
Run Code Online (Sandbox Code Playgroud)
我的WebAPI方法: …
我有这个Web API
post方法来生成PDF:
[HttpPost]
[Route("api/pdf")]
public HttpResponseMessage Post(CustomType type)
{
StreamContent pdfContent = PdfGenerator.GeneratePdf();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = pdfContent;
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "PDFName.pdf"
return response;
}
Run Code Online (Sandbox Code Playgroud)
在AngularJS中我想得到这样的PDF文件:
$http.post("api/pdf", object).then(function (results) {
var data = results.data;
//TODO: got PDF, how to handle?
}, function (results) {
console.log(results);
});
Run Code Online (Sandbox Code Playgroud)
但是我应该如何处理AngularJS中的PDF数据?在iPad上,我希望PDF能够打开,但如果文件被下载或只是在桌面上打开并不重要.
EDIT1:
使用SaveAS JS库我可以在桌面上创建一个可行的解决方案:
$http.post("api/pdf", object).then(function (results) {
var data = results.data;
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, "test.pdf");
}, …
Run Code Online (Sandbox Code Playgroud)