2

I'm trying to create in asp.net 2.0 a web service to download a file (pop up window with Open or Save the file), in this way:

$.ajax({
        type: "POST",
        url: "webservice.asmx/download",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            console.log("donwloaded");
        }
    });

And in "webservice.asmx"

[WebMethod()]
public byte[] DownloadFile(string FName)
{
    System.IO.FileStream fs1 = null;
    fs1 = System.IO.File.Open(FName, FileMode.Open, FileAccess.Read);
    byte[] b1 = new byte[fs1.Length];
    fs1.Read(b1, 0, (int)fs1.Length);
    fs1.Close();
    return b1;
}

[WebMethod]
public void download()
{
    string filename = "test.txt";
    string path = "C:\\test.txt";

    byte[] ls1 = DownloadFile(path);
    HttpResponse response = Context.Response;

    response.Clear();
    response.BufferOutput = true;
    response.ContentType = "application/octet-stream";
    response.ContentEncoding = Encoding.UTF8;
    response.AppendHeader("content-disposition", "attachment; filename=" + filename);

    response.BinaryWrite(ls1);

    response.Flush();
    response.Close();
}

In this way I see the contents of the file (I can't to download the file whith a popup window).

Where I wrong? Is it possible to do this?

thanks in advance

Webman
  • 1,534
  • 3
  • 26
  • 48
  • You would have to open a new window and invoke this ajax part in that new window. – Rameez Ahmed Sayad Sep 20 '13 at 15:48
  • 1
    I think the content type is different for a file in order to appear as a downloadable. – Rameez Ahmed Sayad Sep 20 '13 at 15:54
  • Sorry, but I don't understand what you mean. Actually the ajax call is in click event on aspx page....(for "popup window" I mean the default confirm window of the browser) – Webman Sep 20 '13 at 15:57
  • Oh ok .. I think then popu part is working for you. For the above part , I was telling to open a blank URL with the above JS pasted but you can ignore that. Quite interesting , haven't tried AJAX requests for file downloading , not sure if An AJAX response can come in different contenttype – Rameez Ahmed Sayad Sep 20 '13 at 16:02
  • I think the answer in to this question might help http://stackoverflow.com/questions/16670209/download-excel-file-via-ajax-mvc – Rameez Ahmed Sayad Sep 20 '13 at 16:05

2 Answers2

1

that is not a good way , to make file download thru popup window , just open a new pop and make the url of that window to point to your file or webservice url .

window.open("fileurl"  )
sino
  • 754
  • 1
  • 7
  • 22
0

a good way to do it is simply redirect the browser to the "webservice.asmx/download" instead of calling that via ajax. i.e.

window.location.href = 'webservice.asmx/download';

when browser will detect you returning octet-stream, it will ask to download the file but will not clear/eraze the page you were on.

Artemiy
  • 1,969
  • 14
  • 19