读取流两次? [英] 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 to 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.
我知道我应该如何重置流并将其放回位置 0,但是我该如何以最有效和最正确的方式做到这一点?
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 ?
推荐答案
嗯,最简单的方法是:
file.InputStream.Position = 0;
... 假设流支持搜索.但是,如果您不小心,这可能会对 Image
产生有趣的影响 - 因为它会保留对流的引用.
... 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屋!