3

I'm trying to remotely download a CSV file by calling a WCF service using jQuery. Since the file doesn't actually reside on the server, I've been trying to return it as a stream. Since I use the Content-Disposition header, the client's browser should automatically begin downloading the file with a given filename.

My WCF service method in C#:

[OperationContract()]
public Stream GetCsvFile(int id)
{
    string s = ...;
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv";
    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"file1.csv\"";
    return GenerateStreamFromString(s);
}

public Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

My jQuery AJAX request:

$.ajax({
    type: "POST",
    url: serviceUrl,
    cache: false,
    data: data,
    dataType: "text",
    contentType: "application/json; charset=utf-8",
    success: function() {
        // TODO...
    }
});

This request completes succesfully! And I can see the correct CSV data in the response. However, it does not initiate an actual "file download" action in the browser (testing on Chrome for now) and "file1.csv" is not saved to the client's disk.

In an old VB.NET version of the same application, the following worked in an .aspx page code-behind:

Response.Clear()
Response.ContentType = "text/csv"
Response.AddHeader("content-disposition", "attachment; filename="file1.csv")
Response.Write(s)
Response.End()

This would automatically initiate a file download of "file1.csv". No "Save As" dialog would even show, the file would just download immediately. It was quite cool.

So how come it doesn't work when I try to call a WCF service with jQuery?

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
  • 2
    your ajax call will get a text response. It'll be available to JavaScript only (it'll be "parsed" by jQuery, it won't/can't save it). See [this post here on SO](http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) to see how to start a download from JavaScript. – Adriano Repetti Feb 26 '13 at 15:33
  • This has been answered http://stackoverflow.com/questions/6668776/download-file-through-an-ajax-call-php – Louis Ricci Feb 26 '13 at 15:37

1 Answers1

0

You need to specify proper ContentType on your server side

Piane_Ramso
  • 51
  • 1
  • 8