Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading stream twice?

When I have uploaded an image from my website I need to do 2 things:

  1. read the image dimensions
  2. save the image to the database

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); 

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.

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 ?

like image 922
danielovich Avatar asked Nov 24 '10 11:11

danielovich


People also ask

How to read input stream twice in java?

You can check if mark() and reset() are supported using markSupported() . If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again. InputStream doesn't support 'mark' - you can call mark on an IS but it does nothing.

Can you read a stream twice C#?

You can not read the input stream twice, even if you will try to set the position, it will give error. What you have to do is to create a new stream and use it as many times as you want: MemoryStream newStream = new MemoryStream(); // CopyTo method used to copy the input stream into newStream variable.

How do you reset InputStream?

The java. io. InputStream. reset() method repositions this stream to the position at the time the mark method was last called on this input stream.

What is PushbackInputStream in Java?

A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.


1 Answers

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.

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(); 
like image 58
Jon Skeet Avatar answered Sep 20 '22 16:09

Jon Skeet