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?