WCF 客户端上传文件到服务器端的问题

JokerChenjb 2016-08-31 05:34:18
现在我编写了个简单的基于WCF上传文件的小例程,出现的问题是不能成功进行上传,说是数据流不可读,有大神能解答不。

程序如下:
接口:

namespace file
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“Ifile”。
[ServiceContract]
public interface Ifile
{
[OperationContract]
void UpLoadFile(UpLoadFileMessage request);
}

[MessageContract]
public class UpLoadFileMessage
{
[MessageHeader]
public string FileName { get; set; }
[MessageBodyMember]
public FileStream FileData { get; set; }
}
}


实现:

public void UpLoadFile(UpLoadFileMessage request)
{
string UploadFolder = "D:\\";
string FileName = request.FileName;
Stream sourceStream = request.FileData;
FileStream targetStream = null;

if (!sourceStream.CanRead)
{
throw new Exception("数据流不可读!");
}


if (!Directory.Exists(UploadFolder))
{
Directory.CreateDirectory(UploadFolder);
}

string filePath = UploadFolder + FileName;
using (targetStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Flush();
targetStream.Close();
sourceStream.Close();
}
}


配置:

<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="MyBinding" transferMode="Streamed" messageEncoding="Mtom" maxBufferSize="524288000" maxReceivedMessageSize="524288000" sendTimeout="00:10:00"/>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<dataContractSerializer maxItemsInObjectGraph="524288000"/>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="file.file" behaviorConfiguration="MyBehavior">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyBinding" contract="file.Ifile"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
<system.web>
<compilation debug="true"/></system.web></configuration>


客户端:

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
if(opd.ShowDialog()==DialogResult.OK)
{
textBox1.Text = opd.FileName;
}
}

private void button2_Click(object sender, EventArgs e)
{
string filepath = textBox1.Text;
string FileName = Path.GetFileName(filepath);
FileStream FileData = new FileStream(filepath, FileMode.Open, FileAccess.Read);
file.IfileClient client = new file.IfileClient();
try
{
client.UpLoadFileAsync(FileName, FileData);
MessageBox.Show("成功!");
}
catch
{
MessageBox.Show("错误!");
}



有谁知道原因么???
还有个问题,如果使用的绑定是wsHttpBinding,如何进行文件传输?
...全文
155 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧