I am following the answer in this page (How to set a header for a HTTP GET request, and trigger file download?) in order to call from my client an mvc controller on the server. I need to use a manual ajax call instead of a library/plugin (like fileDownload) because I need to support bearer token. The problem I face is that when I try to download the content, the controller is hit correctly and returns the data of type FileDownloadResult:
public sealed class FileDownloadResult : IHttpActionResult, IDisposable
{
private readonly MemoryStream _dataStream;
private readonly string _fileName;
private readonly string _path;
private readonly string _mimeType;
private readonly string _encoding;
private string MimeType => string.IsNullOrWhiteSpace(_mimeType) ? "application/octet-stream" : _mimeType;
private string Encoding => string.IsNullOrWhiteSpace(_encoding) ? string.Empty : _encoding;
public FileDownloadResult(byte[] fileData, string fileName)
{
_dataStream = new MemoryStream(fileData);
_fileName = fileName;
}
}
...(other overrides methods for FileDownloadResult)...
The problem is that by using the code in the page linked at the beginning, my browser changes page. My code is the following on the client:
function downloadFile(url, data) {
$.ajax({
url: url,
type: "GET",
data: data,
headers: {
Authorization: 'Bearer ' + appsecurity.getBearerTokenWithoutHeader().accessToken
},
success: function (data) {
debugger;
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
}
if I debug the returned data in the browser I see that the type is document .. I don't know if it helps but it's worth mentioning it. How can I solve the problem? Thanks in advance!