I have Export to Excel button in my HTML page, onClick of the button i will send GET request to ASP .Net Web API, which which get data from Database and return HTTPContext binary Response. In the front end, i am getting binary data of the Excel file. How to directly download the file once response came?
HttpContext.Current.Response.ClearContent();
FileStream objFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] excelResponse = new byte[objFileStream.Length];
objFileStream.Read(excelResponse, 0, excelResponse.Length);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
HttpContext.Current.Response.BinaryWrite(excelResponse);
My front end binary content
PKS��J�ɉ�fxl/workbook.xml �(��P�N�0����SA5������8�����4�Z^���8�I�n"�+�Y�����|}����ጉ�V,����V�����v��OJ�=�
How to download as file? I dont want to use form
Below is the AJAX call i am making on click on Export button.
// Make AJAX call
$.ajax({
type: "GET",
url: "http://localhost:8899/api/ExportDataToExcel/",
data: oData,
headers: {
"Authorization": "Bearer " + sToken,
},
success: function (oResult) {
onSuccess(oResult);
},
error: function (oResponse) {
onFailure(oResponse);
}
});
That's all i am doing on Export to Excel button click.
If i use Form submit, then i am getting Authorization denied error, as the API expects bearer token. Following code gives Authorization denied error
var form = document.createElement("form")
form.action = url + 'exportDataToExcel/';
form.method = "GET";
document.body.appendChild(form);
form.submit(true);
document.body.removeChild(form);