简体   繁体   English

如何从 WCF 服务流下载文件?

[英]How to download a file from a WCF service stream?

I'm trying to remotely download a CSV file by calling a WCF service using jQuery.我正在尝试通过使用 jQuery 调用 WCF 服务来远程下载 CSV 文件。 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.由于我使用了Content-Disposition标头,客户端的浏览器应该自动开始下载具有给定文件名的文件。

My WCF service method in C#:我在 C# 中的 WCF 服务方法:

[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:我的 jQuery AJAX 请求:

$.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.我可以在响应中看到正确的 CSV 数据。 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.但是,它不会在浏览器中启动实际的“文件下载”操作(目前在 Chrome 上测试),并且“file1.csv”不会保存到客户端磁盘。

In an old VB.NET version of the same application, the following worked in an .aspx page code-behind:在同一应用程序的旧 VB.NET 版本中,以下代码在 .aspx 页面代码隐藏中起作用:

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".这将自动启动“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?那么为什么当我尝试使用 jQuery 调用 WCF 服务时它不起作用呢?

您需要在服务器端指定正确的 ContentType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM