我有WCF服务,并假设我有一个包含两页或更多页内容的Excel文件。假设文件为C:\reports\customers.xls
,其中customers.xls
文件有两页:
这是我尝试的代码:
选项1:
[WebGet(UriTemplate = "Download/Customers")]
public virtual Stream DownloadCustomers()
{
if (WebOperationContext.Current == null)
{
throw new Exception("WebOperationContext not set");
}
var file = Path.Combine(@"C:\reports", "customers.xls");
var fileName = Path.GetFileName(file);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
return File.OpenRead(file);
}
选项2:
[WebGet(UriTemplate = "Download/Customers")]
public virtual Stream DownloadCustomers()
{
if (WebOperationContext.Current == null)
{
throw new Exception("WebOperationContext not set");
}
var file = Path.Combine(@"C:\reports", "customers.xls");
var fileName = Path.GetFileName(file);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
MemoryStream stream = new MemoryStream();
var contentInBytes = File.ReadAllBytes(file);
stream.Write(contentInBytes, 0, contentInBytes.Length);
stream.Position = 0;
stream.Flush();
return stream;
}
我尝试了两个选项,但两个选项均无效。这两个选项的结果都是下载了一个空文件(0字节)。
如何下载文件及其所有内容?服务器端代码应该是什么样子,以便下载文件及其所有内容?
谢谢
编辑:-我终于自己解决了,这是方法:
解决方案:
我确定其他人也会遇到相同的问题,并希望分享我的解决方案:
首先,我必须创建一个DataContract,如下所示:
[DataContract]
public class FileStreamDto
{
[DataMember]
public string FileName { get; set; }
[DataMember]
public Stream FileStream { get; set; }
}
下一步,我必须按以下方式更改服务:
[WebGet(UriTemplate = "Download/Customers")]
public virtual FileStreamDto DownloadCustomers()
{
if (WebOperationContext.Current == null)
{
throw new Exception("WebOperationContext is not set");
}
var file = Path.Combine(@"C:\reports", "customers.xls");
var fileName = Path.GetFileName(file);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
return new FileStreamDto {
FileName = fileName,
FileStream = File.OpenRead(file)
};
}
第三个也是非常关键的串行器(主要是json),需要知道返回Stream而不是简单json对象的方法。可以完成以下操作:
public Message SerializeResponse(..., object result)
{
if (WebOperationContext.Current
.OutgoingResponse.ContentType == "application/octet-stream")
{
return WebOperationContext.Current
.CreateStreamResponse(((FileStreamDto)result).FileStream,
"application/octet-stream");
}
// the rest of JSON or XML serialier goes here....
.
.
.
}
我希望它能对某人有所帮助。