WCF接收图像服务

时间:2020-03-06 14:27:28  来源:igfitidea点击:

创建用于接受图像的Web服务的最佳方法是什么。
图像可能很大,我不想更改Web应用程序的默认接收大小。
我写了一个接受二进制图像的文件,但我觉得必须有一个更好的选择。

解决方案

该图像在哪里"住"?是否可以在本地文件系统或者Web上访问它?如果是这样,我建议Web服务接受URI(可以是URL或者本地文件)并将其作为Stream打开,然后使用StreamReader读取其内容。

示例(但将异常包装在FaultExceptions中,并添加FaultContractAttributes):

using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;

[OperationContract]
public void FetchImage(Uri url)
{
    // Validate url

    if (url == null)
    {
        throw new ArgumentNullException(url);
    }

    // If the service doesn't know how to resolve relative URI paths

    /*if (!uri.IsAbsoluteUri)
    {
        throw new ArgumentException("Must be absolute.", url);
    }*/

    // Download and load the image

    Image image = new Func<Bitmap>(() =>
    {
        try
        {
            using (WebClient downloader = new WebClient())
            {
                return new Bitmap(downloader.OpenRead(url));
            }
        }
        catch (ArgumentException exception)
        {
            throw new ResourceNotImageException(url, exception);
        }
        catch (WebException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }

        // IOException and SocketException are not wrapped by WebException :(            

        catch (IOException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }
        catch (SocketException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }
    })();

    // Do something with image

}

我们不能使用FTP将图像上传到服务器,然后服务器(以及WCF服务)轻松访问该图像吗?这样,我们就无需考虑接收大小设置等问题。

至少,这就是我做到的方式。