读流两次? [英] Reading stream twice?
问题描述
当我从我的网站上传的图片,我需要做两件事情:
When I have uploaded an image from my website I need to do 2 things:
- 读取图像尺寸
- 将图像保存到数据库中
我做的是阅读的图像流成Image对象的第一件事,像这样:
the first thing I do is reading the image stream into an Image object, like so:
var file = Request.Files["logo"];
Image FullsizeImage = Image.FromStream(file.InputStream);
我做的下一件事就是拯救文件对象数据库(LINQ到SQL) 。但是,当我试图将图像保存到数据库,从该文件的流已经是现在的位置在流的末尾,似乎没有数据存在。
the next thing I do is to save the "file" object to the database (LINQ to SQL). BUT, when I try to save the image to database, the stream from the file has it's postion at the end of the stream, and it seems no data is present.
我知道我应该somwhow重置流,并把它放回位置0,但我怎么做,最effiecent和正确的方法是什么?
I know I should somwhow reset the stream and put it back into position 0, but how do I do that the most effiecent and correct way ?
推荐答案
好了,最简单的方法是:
Well, the simplest way is:
file.InputStream.Position = 0;
...假设流支持寻求。但是,这可能会做有趣的事情给图片
如果你不小心 - 因为它会保留到流的引用
... assuming the stream supports seeking. However, That may do interesting things to the Image
if you're not careful - because it will have retained a reference to the stream.
您可能是最好关闭数据加载到一个字节数组,然后创建两个单独的的MemoryStream
从它的对象,如果你仍然需要。如果您使用.NET 4中,很容易一个流复制到另一个:
You may be best off loading the data into a byte array, and then creating two separate MemoryStream
objects from it if you still need to. If you're using .NET 4, it's easy to copy one stream to another:
MemoryStream ms = new MemoryStream();
Request.Files["logo"].InputStream.CopyTo(ms);
byte[] data = ms.ToArray();
这篇关于读流两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!