"參數不能傳送較大的檔案"
原來是要把檔案用Stream 或 byte[]的方式放在服務參數的方式來實現Server - Client互傳檔案時
會一直出現記憶體配置錯誤
WCF服務契約中有預設傳送內容大小
所以要實現這的方式需要手動更改服務契約內容
如下修改範例~
1.打開Windows Visual Studio 2010(我只有這版...
新增一個C#的WCF服務應用程式,做為Server端(在此範例中取名叫 WCFServerSite)
另外在新增一C#的Windows Form應用程式,做為Client端(WCFClientStie)
2.在WCFServerSite的IService1.cs中增加一OperationContract
// 增加新的服務
[OperationContract]
string UploadData(Stream SourceStream);
2.在WCFServerSite的Service1.svc.cs中定義 UploadData的內容
public string UploadData(Stream SourceStream)
{
byte[] buffer;
FileStream TargetFS = new FileStream( System.Web.Hosting.HostingEnvironment.MapPath("~") + "\\Temp.file", FileMode.Create);
try
{
BinaryReader BR = new BinaryReader(SourceStream);
BinaryWriter BW = new BinaryWriter(TargetFS);
do
{
buffer = BR.ReadBytes(1024);//可自行調整
BW.Write(buffer);
}
while (buffer.Length > 0);
BW.Close();
}
finally
{
SourceStream.Close();
TargetFS.Close();
}
return string.Format("Good Job");
}
ps. 由於UploadData中使用到寫檔指令,須確認IIS是否有開起寫入權限。
3.將Service發布到IIS中(此範例所設定的發佈路徑是 http://localhost/WCFServerSite/Service1.svc)
Client端中參照的命名空間名稱設為SR
在Form中新增一Button和OpenFileDialog元件
Button內容如下:
private void button1_Click(object sender, EventArgs e)
{
SR.Service1Client SRC = new SR.Service1Client();
openFileDialog1.ShowDialog();
try
{
MessageBox.Show(SRC.UploadData(openFileDialog1.OpenFile()));
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
確認Client端可正常使用服務參照,且使用一般小檔(1-3kb)傳輸。
4.修改Server端 Web.config設定
設定如下:
5.修改Client端 app.config設定
設定如下:
6.這樣就完成了~
盡量不要為求方便設定太大,少量多傳才是好的架構!


沒有留言:
張貼留言