C# WCF正在将HttpPostedFileBase发送到服务以进行处理
我需要在用户单击“上载文件”按钮后,从网页前端将HttpPostedFileBase发送到服务器上运行的wcf服务进行处理。我首先在服务合同中使用了HttpPostedFileBase,但它不起作用。然后,我尝试将HttpPostedFileBase放入数据契约中,但仍然不起作用。我花了两天时间才解决了那个问题。下面是方法: 在役合同:C# WCF正在将HttpPostedFileBase发送到服务以进行处理,c#,asp.net-mvc,wcf,C#,Asp.net Mvc,Wcf,我需要在用户单击“上载文件”按钮后,从网页前端将HttpPostedFileBase发送到服务器上运行的wcf服务进行处理。我首先在服务合同中使用了HttpPostedFileBase,但它不起作用。然后,我尝试将HttpPostedFileBase放入数据契约中,但仍然不起作用。我花了两天时间才解决了那个问题。下面是方法: 在役合同: [ServiceContract] public interface IFileImportWcf { [OperationContract]
[ServiceContract]
public interface IFileImportWcf
{
[OperationContract]
string FileImport(byte[] file);
}
并发现这两种方法可以将byte[]转换为stream,反之亦然
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
在控制器中:
[HttpPost]
public ActionResult Import(HttpPostedFileBase attachment)
{
//convert HttpPostedFileBase to bytes[]
var binReader = new BinaryReader(attachment.InputStream);
var file = binReader.ReadBytes(attachment.ContentLength);
//call wcf service
var wcfClient = new ImportFileWcfClient();
wcfClient.FileImport(file);
}
我的问题是:向wcf服务发送HttpPostedFileBase的更好方法是什么?您需要在这里使用
正如我从您的问题中了解到的,您可以控制您的WCF服务合同
如果您将合同更改为以下内容:
[ServiceContract]
public interface IFileImportWcf
{
[OperationContract]
string FileImport(Stream file);
}
然后您将能够在客户端使用它:
[HttpPost]
public ActionResult Import(HttpPostedFileBase attachment)
{
var wcfClient = new ImportFileWcfClient();
wcfClient.FileImport(attachment.InputStream);
}
请注意,您需要在配置中启用流式传输
<binding name="ExampleBinding" transferMode="Streamed"/>
(有关更多详细信息,请参见上面的链接)实际上,传输模式应该是“流式”的,如: