首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

RESTful WCF 實作檔案上傳下載:以 Raw/Stream 傳輸二進位資料

     編輯:關於.NET

核心觀念:Raw 傳輸支援任意格式

WCF REST 不僅支援 XML/JSON,還支援 原生資料。當回傳值或參數為 System.IO.Stream(或衍生類型),並搭配 HTTP Content-Type 標頭,即可實作二進位檔案上傳/下載,保持資料原始格式不變。

完整範例架構

方案 WcfBinaryRestful 包含四個專案:

專案說明
WcfBinaryRestful.Contracts服務合約
WcfBinaryRestful.Service服務實作
WcfBinaryRestful.HostConsole 裝載程式
WcfBinaryRestful.ClientWinForms 客戶端

方案結構圖

1. 服務合約

[ServiceContract]
public interface IService
{
    [OperationContract]
    System.IO.Stream ReadImg();          // 下載
    [OperationContract]
    void ReceiveImg(System.IO.Stream stream); // 上傳
}

2. 服務實作

public class Service : Contracts.IService
{
    [WebInvoke(Method = "*", UriTemplate = "ReadImg")]
    public System.IO.Stream ReadImg()
    {
        string path = Path.Combine(Environment.CurrentDirectory, "jillzhanglogo.jpg");
        FileStream fs = new FileStream(path, FileMode.Open);
        Thread.Sleep(2000); // 模擬延遲
        WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
        return fs;
    }

    [WebInvoke(Method = "*", UriTemplate = "ReceiveImg")]
    public void ReceiveImg(System.IO.Stream stream)
    {
        Debug.WriteLine(WebOperationContext.Current.IncomingRequest.ContentType);
        Thread.Sleep(3000);
        string path = Path.Combine(Environment.CurrentDirectory, "ReceiveImg.jpg");
        Image bmp = Bitmap.FromStream(stream);
        bmp.Save(path);
    }
}

關鍵點:設定 OutgoingResponse.ContentType = "image/jpeg";使用 Bitmap.FromStream 直接處理上傳串流。

3. 主機組態

<endpoint address="" binding="webHttpBinding"
    contract="WcfBinaryRestful.Contracts.IService"
    behaviorConfiguration="WcfBinaryRestfulBehavior" />
<behavior name="WcfBinaryRestfulBehavior">
    <webHttp/>
</behavior>

使用 webHttpBinding + <webHttp/> 行為啟用 REST。

4. 客戶端

使用 System.Net.WebClient 非同步上傳/下載:

  • 下載:DownloadFileAsync + DownloadFileCompleted 事件
  • 上傳:UploadDataAsync + UploadDataCompleted,需加 Headers.Add("Content-Type", "image/jpeg")

服務主控台運行畫面 客戶端介面 下載成功提示 下載的圖片檔案 上傳成功提示 伺服器接收的上傳檔案

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved