将文件从Flex上传到WCF REST Stream问题(如何在REST WS中解码多部分表单post)

该系统是与WCF REST Web服务通信的Flex应用程序。 我正在尝试将文件从Flex应用程序上传到服务器并遇到一些问题,我希望有人能够提供帮助。 我在Flex应用程序中使用FileReference来浏览和上传此处定义的文件:

http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/

然后我在WCF REST Web服务(使用WCF 4 REST服务的项目类型)中接收文件作为Stream(在调试器中显示为System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream)

[WebInvoke(Method = "POST", UriTemplate = "_test/upload")] public void UploadImage(Stream data) { // TODO: just hardcode filename for now var filepath = HttpContext.Current.Server.MapPath(@"~\_test\testfile.txt"); using (Stream file = File.OpenWrite(filepath)) { CopyStream(data, file); } } private static void CopyStream(Stream input, Stream output) { var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } 

注意:此post中使用的CopyStream方法: 如何将流保存到C#中的文件?

该文件保存没有任何问题。 我遇到的问题是该文件包含的信息比我想要的多。 以下是保存文件的内容(源文件仅包含“这是文件的内容”):

 ------------ae0ae0Ef1ae0Ef1ae0gL6gL6Ij5cH2 Content-Disposition: form-data; name="Filename" testfile.txt ------------ae0ae0Ef1ae0Ef1ae0gL6gL6Ij5cH2 Content-Disposition: form-data; name="Filedata"; filename="testfile.txt" Content-Type: application/octet-stream THIS IS THE CONTENT OF THE FILE ------------ae0ae0Ef1ae0Ef1ae0gL6gL6Ij5cH2 Content-Disposition: form-data; name="Upload" Submit Query ------------ae0ae0Ef1ae0Ef1ae0gL6gL6Ij5cH2-- 

内容与Adobe文档中描述的内容完全相同: http : //help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html

C#中是否有任何设施可以从Stream获取文件内容?

编辑(3/24 8:15 pm) :Flex应用程序发送的是Multipart表单POST。 如何解码由Stream参数表示的多部分正文数据并删除多部分正文的各个部分?

编辑(3/25上午10点) :一些相关的Stack Overflowpost:
WCF服务接受post编码的multipart / form-data
将multipart / form-data发布到WCF REST服务:操作更改

编辑(3/25上午10:45) :找到一个非常好的多部分解析器:
http://antscode.blogspot.com/2009/11/parsing-multipart-form-data-in-wcf.html

提前致谢。

我在这里开源了一个C#Http表单解析器。

这比在CodePlex上提到的另一个稍微灵活一些,因为您可以将它用于Multipart和非Multipart form-data ,并且它还为您提供在Dictionary对象中格式化的其他表单参数。

这可以使用如下:

非多

 public void Login(Stream stream) { string username = null; string password = null; HttpContentParser parser = new HttpContentParser(data); if (parser.Success) { username = HttpUtility.UrlDecode(parser.Parameters["username"]); password = HttpUtility.UrlDecode(parser.Parameters["password"]); } } 

 public void Upload(Stream stream) { HttpMultipartParser parser = new HttpMultipartParser(data, "image"); if (parser.Success) { string user = HttpUtility.UrlDecode(parser.Parameters["user"]); string title = HttpUtility.UrlDecode(parser.Parameters["title"]); // Save the file somewhere File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents); } } 

感谢Anthony在http://antscode.blogspot.com/上为多部分解析器工作得很好(对于图像,txt文件等)。

http://antscode.blogspot.com/2009/11/parsing-multipart-form-data-in-wcf.html

我有一些基于字符串解析的解析器问题,特别是对于大文件,我发现它会耗尽内存而无法解析二进制数据。

为了解决这些问题,我在这里开放了自己的C#multipart / form-data解析器

有关详细信息,请参阅我的答案。