如何从WCF服务流下载文件? [英] How to download a file from a WCF service stream?

查看:124
本文介绍了如何从WCF服务流下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用jQuery调用WCF服务来远程下载CSV文件.由于该文件实际上并不驻留在服务器上,因此我一直试图将其作为流返回.由于我使用Content-Disposition标头,因此客户端的浏览器应自动开始下载具有给定文件名的文件.

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.

我在C#中的WCF服务方法:

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;
}

我的jQuery AJAX请求:

My jQuery AJAX request:

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

此请求成功完成!而且我可以在响应中看到正确的CSV数据.但是,它不会在浏览器中启动实际的文件下载"操作(目前在Chrome上进行测试),并且"file1.csv"未保存到客户端磁盘上.

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.

在同一应用程序的旧VB.NET版本中,以下代码在.aspx页的代码隐藏中起作用:

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()

这将自动启动文件"file1.csv"的下载.甚至不会显示另存为"对话框,该文件将立即下载.太酷了.

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.

那么当我尝试使用jQuery调用WCF服务时,为什么它不起作用?

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

推荐答案

您需要在服务器端指定适当的ContentType

You need to specify proper ContentType on your server side

这篇关于如何从WCF服务流下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆