I need to download a file located in the App_Data folder of my project, all permissions are granted, I have the following code to download an .xlsx file by calling a WebService in C#, the result of the process does not throw an error, but it does not download the file in the explorer and in the preview when inspecting the process shows unknown characters.
AJAX Jquery code:
function DOWNLOAD_EXCEL_SERVICES() {
$.ajax({
type: 'POST',
url: '../WebServices/getJSON.asmx/DOWNLOAD_EXCEL_SERVICES',
contentType: 'application/x-msexcel',
success: OnSuccess,
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function OnSuccess() {
console.log("donloading-services");
}
}
WebService C# code:
[WebMethod]
public void DOWNLOAD_EXCEL_SERVICES()
{
var path = Server.MapPath("~/App_Data//");
string filename = "SERVICES.xlsx";
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
byte[] Content = File.ReadAllBytes(path + "SERVICES.xlsx");
Response.ContentType = "application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + "\"");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.Flush();
}
Output of Process inspecting in Chrome:
Additionally if I use Response.End()
instead of Response.flush()
just check "Proces was being aborted", even though I use a try-catch structure I get the same result, it doesn't drop the file.
The problem is that you are doing an AJAX post, so the file is sent to the stream that receives your $.ajax request.
In other words, so that you can download it you should make a link that goes directly to the web service, or from JavaScript you could do it like this:
I hope it helps you.
Luck!
Completing Gustavo Cantero 's answer, my Javascript code looks like this:
and finally looking for similar problems, for the request to the WebService to work directly you have to add the following tags to the file
Web.config
:My Web Service remains unedited; solved in my case, thanks.