Do not download the file to the browser using OutputStream.Write in ASP.NET WebService C #

0

I need to download a file located in the App_Data folder of my project, all the permissions are granted, I have the following code to download an .xlsx file by calling a WebService in C #, the result of the process is not error, but it does not download the file in the browser 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();
}

Process Output inspecting in Chrome:

Additionally, if I use Response.End() instead of Response.flush() simply mark "Proces was being aborted", even if I use a try-catch structure I get the same result, it does not release the file.

    
asked by Ricardo Soria 29.10.2018 в 22:36
source

2 answers

0

Completing with the response of Gustavo Cantero my Javascript code remains as follows:

function DOWNLOAD_EXCEL_SERVICES() {
    window.location.href = '../WebServices/getJSON.asmx/DOWNLOAD_EXCEL_SERVICES';
}

and finally looking for similar problems, so that the request to the WebService works directly you have to add the following tags to the file Web.config :

<configuration>

    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>

</configuration>

My Web Service remains unedited; was solved in my case, Thank you.

    
answered by 29.10.2018 / 23:51
source
1

The problem is that you are doing an AJAX post, so the file is sent to the stream that receives your $ .ajax request.

That is, 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:

function DOWNLOAD_EXCEL_SERVICES() {
    window.location = '../WebServices/getJSON.asmx/DOWNLOAD_EXCEL_SERVICES';
}

I hope it serves you.

Good luck!

    
answered by 29.10.2018 в 23:21