Reputation: 208
I have tried to download a file from a method of my Web API Controller (Asp.net MVC 6). So, my file is created in a api controller and I want download my file, already in excel format, with angularjs. But, I don't know how to do.
Here is my method in my api controller: (it works, I already use this methods and class in an another project Asp.net without angularj)
#region downloadFile
[Route("Download")]
public ActionResult Download()
{
string companyName = Context.Session.GetString("companyName") as string;
string fileDownloadName = Context.Session.GetString("fileDownloadName") as string;
string baseFolder = System.IO.Path.Combine("C:\\Temp");
string folder = System.IO.Path.Combine(baseFolder, companyName);
TempFile tempFile = new TempFile(folder, fileDownloadName);
tempFile.FindFileInDirectory();
return File(tempFile._pathDirectory + "\\"+tempFile._fileName, "Application/" + tempFile._fileExt, tempFile._fileName);
}
#endregion
This method returns an excel file. Now, I would download this file that is send in angularjs with a http request.
I have tried to use the method saveAs from fileSaver.js. I have added the js in my project but when I want use it, the method is always undefined.
var requestDownloadFile =
$http({
url: '/api/customers/Download'
, responseType: 'arraybuffer'
, headers: {
'contentType': 'application/json'
, 'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
});
requestDownloadFile.success(function (data) {
saveAs(data, 'test.xlsx');
});
I tried to use this too in my success method:
var blob = new Blob([data], { type: "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" })
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
It run a download file, but the file is corrupted.
So it's not realy effective because I have created a file in API and I have tried to recover an arrayBuffer but I'm blocked so I try.
All support is welcome. Thanks
Upvotes: 0
Views: 1819
Reputation: 208
So, I complicated life. I just had to do this in the success:
window.open('/api/customers/Download', '_blank', '');
window.open('link/to/method/api', '_blank', '');
Upvotes: 1