如何将我的流(图像数据)转换回文件
我有一个 WCF 安静服务,我正在尝试将图像上传到其中。我有一个非常基本的方法,它接受流作为唯一的参数,并在合同中定义为:
[OperationContract]
[WebInvoke(UriTemplate = "ReviewImage", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
ReviewImage UploadImage(Stream data);
我实际上是从闪存使用此服务(这是相当无关紧要的),它从文件系统中选择一个文件并通过服务网址。
这一切似乎都有效,向 UploadImage 方法添加断点会按预期中断。
如果我想将此文件保存回磁盘,是否只需将此 Stream 对象读入在某处创建该文件的 FileStream 对象即可?有点像这样?当我实际执行此操作时,文件无法作为图像打开。我确信我在这里遗漏了一个关键知识。我的流实际上只包含图像字节还是包含更多字节?
接受答案后编辑:
问题在于 Flash 将图像上传编码为 multipart/form-data,这会向邮件正文添加附加数据。我使用 MultipartParser 此处找到来获取实际图像并写入磁盘。
I have a WCF restful service that I'm trying to upload an image to. I have a very basic metod that accepts a stream as it's only parameter and is defined in the contract as:
[OperationContract]
[WebInvoke(UriTemplate = "ReviewImage", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
ReviewImage UploadImage(Stream data);
I'm actually consuming this service from flash (which is fairly inconsequntial) which selects a file from the file system and uploads it through the service url.
It all works seems to work, adding a breakpoint to the UploadImage method breaks as expected.
If I wanted to save this file back to disk, is it just a case of reading this Stream object into a FileStream object that creates the file somewhere? A bit like the this? When i do actually do this the file can not be opened as an image. I'm sure i'm missing a key piece of knowledge here. Does my stream actually contain just the image bytes or does it contain more than that?
EDIT AFTER ANSWER ACCEPTED:
The problem was that flash encodes image uploads as multipart/form-data which was adding aditional data to the message body. I use the MultipartParser found here to get to the actual image and write to disk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要流未更改原始文件,您所需要做的就是打开一个新文件流并将图像流复制到其中(确保您位于流的开头并确保使用可靠的字符串复制算法,如您链接的算法)。它(通常)就这么简单。如果向您发送文件的应用程序与流发生混乱,情况可能会变得复杂。但只有一种方法可以查明情况是否如此......
As long as the stream was unaltered from the original file, all you need to do is open a new file stream and copy the image stream into it (making sure you're at the start of the stream and making sure you use a reliable string copying algorithm like the one you linked). Its (normally) just as simple as that. It may get complicated if the app sending you the file messes with the stream. But there's only one way to find out if that's the case...
我个人会在 System.Draming 命名空间中使用 Bitmap 类(您也需要添加对 System.Drawing 的引用),以确保正确的编码。
I would use the Bitmap class in the System.Draming namespace (you need to add a reference to System.Drawing too) personally, that ensure sthe correct encoding.