WCF - 通过 http 流式文件上传 [英] WCF - Streaming file upload over http

查看:61
本文介绍了WCF - 通过 http 流式文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个 WCF 服务,该服务将允许我的 WPF 桌面客户端将文件上传到服务器.

I am trying to build a WCF service that will allow my WPF desktop clients to upload files to a server.

我改编了代码项目中的代码示例(WCF Streaming: Upload/Download Files OverHTTP),我也看过几个 SO 帖子,但似乎无法正常工作.

I adapted a code sample from The Code Project (WCF Streaming: Upload/Download Files Over HTTP) and I've looked at several SO posts as well, but can't seem to get this working.

当我执行代码时,它在服务器尝试读取已通过接口传递的流时失败并出现空引用异常.

When I execute the code, it fails with a null reference exception at the point that the server tries to read the stream that has been passed through the interface.

在这一点上,我很迷茫,不知道如何解决这个问题.任何建议表示赞赏.

At this point, I am rather lost and don't know how to fix this up. Any suggestions are appreciated.

代码示例如下:

CustomerDocumentModel 是我通过 WCF 接口通过流读取客户端文件的数据元素:

CustomerDocumentModel is the data element that I pass through the WCF interface with the stream to read the client side file:

[DataContract]
[KnownType(typeof(System.IO.FileStream))]
public class CustomerDocumentModel : IDisposable
{
    public CustomerDocumentModel()
    {
    }

    public CustomerDocumentModel(string documentName, string path)
    {
        DocumentName = documentName;
        Path = path;
    }

    [DataMember]
    public string DocumentName;

    [DataMember]
    public string Path;

    [DataMember]
    public System.IO.Stream FileByteStream;

    public void Dispose()
    { 
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }
}

IBillingService 是我的 WCF 服务的接口定义:

IBillingService is the interface definition for my WCF service:

[ServiceContract]
public interface IBillingService
{
    // other methods redacted...

    [OperationContract]
    void UploadCustomerDocument(CustomerDocumentModel model);
}

BillingService 类实现了 WCF 服务:

The class BillingService implements the WCF service:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BillingService : IBillingService
{
    // Other methods redacted ...

    public void UploadCustomerDocument(CustomerDocumentModel model)
    {
        string path = HttpContext.Current.Server.MapPath(
            String.Format("/Documents/{1}",
                model.DocumentName));

        using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            const int bufferSize = 4096;
            byte[] buffer = new byte[bufferSize];

            int size = 0;
            try
            {
                // The following Read() fails with a NullReferenceException
                while ((size = model.FileByteStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    stream.Write(buffer, 0, size);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
            stream.Close();
            model.FileByteStream.Close();
            }
        }
    }
}

我的 WCF Web 服务器上的 web.config 中的一些相关内容:

A few relevant bits from the web.config on my WCF web server:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="360"/>
</system.web>

<system.serviceModel>
    <serviceHostingEnvironment
        aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <bindings>
        <basicHttpBinding>
            <binding name="userHttps" transferMode="Streamed" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                <security mode="None" />
            </binding>
        </basicHttpBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior name="">
                <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
                <serviceDebug includeExceptionDetailInFaults="true" />
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

客户端是一个 WPF/MVVM 应用,它创建一个 CustomerDocumentModel 模型,使用 OpenFileDialog 打开() 文件流,然后将该模型传递给 WCF 服务上的 UploadCustomerDocument 方法.

The client is a WPF/MVVM app that creates a CustomerDocumentModel model, uses an OpenFileDialog to Open() the file stream and then passes the model to the UploadCustomerDocument method on WCF Service.

如果我遗漏了任何相关细节,请询问.

If I am missing any relevant details, please ask.

推荐答案

我知道这个问题的回复很晚,我相信你也一定已经解决了你的问题.这可能对其他人有帮助:-)

I know this rather very late reply for your question and I'm sure you must have resolved your problem as well. This could be helpful to someone else :-)

使用 Messagecontract 而不是 Datacontract,只有一个 MessageBodyMember 数据类型为 Stream,其余参数均为 MessageHeader.例子如下:

Use Messagecontract over Datacontract and only one MessageBodyMember with datatype Stream and rest all parameter are MessageHeader. Here is the example:

[MessageContract]

    public class CustomerDocumentModel : IDisposable
    {

        public CustomerDocumentModel(string documentName, string path)
        {
            DocumentName = documentName;
            Path = path;
        }

        [MessageHeader]
        public string DocumentName{get;set;}

        [MessageHeader]
        public string Path{get;set;}

        [MessageBodyMember]
        public System.IO.Stream FileByteStream{get;set;}

        public void Dispose()
        { 
            if (FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }

注意:确保您的配置传输模式是 StreamedResponse,您也可能希望将 MessageEncoding 更改为 MTOM 以获得更好的性能.

Note: Make sure your in your configuration transfer mode is StreamedResponse, also you may want to change the MessageEncoding to MTOM for better performance.

public void UploadCustomerDocument(CustomerDocumentModel model)
{
        var filename = //your file name and path;
        using (var fs = new FileStream(filename, FileMode.Create))

        {
               model.FileByteStream.CopyTo(fs);
        }
}

这篇关于WCF - 通过 http 流式文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆