REST风格的WCF服务的图片上传问题 [英] RESTful WCF service image upload problem

查看:102
本文介绍了REST风格的WCF服务的图片上传问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1 namespace Uploader  
2 {  
3     using System;  
4     using System.IO;  
5     using System.ServiceModel;  
6     using System.ServiceModel.Description;  
7     using System.ServiceModel.Web;  
8     using System.Drawing;  
9     using System.Drawing.Imaging;  
10     using System.Net;  
11     using System.Xml;  
12   
13     [ServiceContract(Namespace = "http://Uploader")]  
14     public interface IUploaderService  
15     {  
16         [OperationContract, WebInvoke(Method = "POST",UriTemplate = "File/{fileName}")]  
17         bool UploadFile(string fileName, Stream fileContents);  
18     }  
19   
20     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]  
21     public class UploaderService : IUploaderService  
22     {  
23         public bool UploadFile(string fileName, Stream fileContents)  
24         {  
25             return true;  
26         }  
27     }  
28   
29     class Program  
30     {  
31         static void Main()  
32         {  
33             var host = new   
34                 ServiceHost(typeof (UploaderService),   
35                 new Uri("http://localhost:8080/Uploader"));  
36             host.AddServiceEndpoint("Uploader.IUploaderService",   
37                 new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());  
38             try  
39             {  
40                 host.Open();  
41                 Console.WriteLine(host.BaseAddresses[0].AbsoluteUri + " running.");  
42                 Console.WriteLine();  
43                 var uri = "http://localhost:8080/Uploader/file.jpg";  
44                 var req = WebRequest.Create(uri) as HttpWebRequest;  
45                 if (req != null)  
46                 {  
47                     req.Method = "POST";  
48                     req.ContentType = "image/jpeg";  
49                     var reqStream = req.GetRequestStream();  
50                   
51                     var imageStream = new MemoryStream();  
52                     using (var i = Image.FromFile(@"c:\photo.jpg"))   
53                         i.Save(imageStream, ImageFormat.Jpeg);  
54                       
55                     var imageArray = imageStream.ToArray();  
56                     reqStream.Write(imageArray, 0, imageArray.Length);  
57                     reqStream.Close();  
58                     var resp = (HttpWebResponse)req.GetResponse();  
59                     var r = new XmlTextReader(resp.GetResponseStream());  
60                     if (r.Read())  
61                     {  
62                         Console.WriteLine(r.ReadString());      
63                     }  
64                 }  
65                 Console.WriteLine("Press <ENTER> to quit.");  
66                 Console.ReadLine();  
67             }  
68             catch (Exception ex)  
69             {  
70                 Console.WriteLine(ex.Message);  
71                 Console.ReadKey();  
72             }  
73             finally  
74             {  
75                 if (host.State == CommunicationState.Faulted)  
76                     host.Abort();  
77                 else  
78                     host.Close();  
79             }  
80         }  
81     }  
82 }  
83   
84

你好,希望你能帮助....

Hi, hope you can help....

我创建一个简单的应用程序(可能是网页),将有一个简单的用户界面,将来自外部装置上载文件,应用程序/网页将通过的autorun.inf当用户插入一个设备插入有个人电脑启动。 web服务将执行文件链接到管理系统等的复杂的工作这将使不能使用文件IT文盲用户探索的文件提交给管理系统...!

I am creating a simple app(maybe webpage) that will have a simple UI and will upload files from an external device, the app/webpage will be started via autorun.inf when the user plugs a device into there PC. The webservice will perform the complex job of linking the file to the management system etc. This will enable the IT illiterate users that can't use file explore to submit files to the the management system...!

我的是,我的RESTful serivce是给我一个400错误时,内容类型是一个形象问题/ JPEG ..
它工作正常的文本/ plain或text / xml的(看到博客文章)

The problem I have is that my RESTful serivce is giving me a 400 error when the content type is a image/jpeg.. It works fine for text/plain or text/xml (see Blog Post)

由于
Ĵ

推荐答案

你可以尝试超越任何内容类型和上传的所有文件,应用程序/八位字节流,或使用IOperationBehavior text / plain的。

You can try to override any content-type and upload all files as application/octet-stream, or text/plain using an IOperationBehavior.

public class WebContentTypeAttribute : Attribute, IOperationBehavior, IDispatchMessageFormatter
{
    private IDispatchMessageFormatter innerFormatter;
    public string ContentTypeOverride { get; set; }

    public WebContentTypeAttribute(string contentTypeOverride)
    {
        this.ContentTypeOverride = contentTypeOverride;
    }


    // IOperationBehavior
    public void Validate(OperationDescription operationDescription)
    {

    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        innerFormatter = dispatchOperation.Formatter;
        dispatchOperation.Formatter = this;
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {

    }

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {

    }

    // IDispatchMessageFormatter
    public void DeserializeRequest(Message message, object[] parameters)
    {
        if (message == null)
            return;

        if (string.IsNullOrEmpty(ContentTypeOverride))
            return;

        var httpRequest = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
        httpRequest.Headers["Content-Type"] = ContentTypeOverride;
    }

    public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
    {
        return innerFormatter.SerializeReply(messageVersion, parameters, result);
    }
}

和你将不得不修改您的服务合同看像这样的

And you would have to modify your Service contract to look like this one

[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "File/{fileName}")]
[WebContentType("application/octet-stream")]
bool UploadFile(string fileName, Stream fileContents);



尽管如此,如果你是从网页上载,也不会在数据张贴在一个多/表单数据格式?

Although, if you are uploading from a webpage, wouldn't the data be posted in a multipart/form-data format?

这篇关于REST风格的WCF服务的图片上传问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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