开发者

Write Binary File

I am reading data from an IPhone App that uses h开发者_开发问答ttp POST to transfer the image to the Server I can read this into a an binary and it does write to a file (See below) the issue I have is when I open the image it fails.

You can see the code from the Iphone on this post: asp http POST Read Data

Code:

byte[] buffer = new byte[Request.ContentLength];
using (BinaryReader br = new BinaryReader(Request.InputStream))
    br.Read(buffer, 0, buffer.Length);

string fileName = @"C:\test\test.jpg";
FileStream fs = new FileStream(fileName, FileMode.Create, 
    FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffer);
bw.Close();

The image Content-Type is application/octet-stream

Can anyone shine any light onto this please.


Perhaps the Request.ContentLength was not set correctly? I know from bitter experience that it's not always safe to trust it. :-(

You can read the stream without knowing the length in advance like this:

const int bufferSize = 1024 * 64; // pick any reasonable buffer size
List<byte> buffer = new List<byte>();
using(Stream stream = new BufferedStream(request.InputStream, bufferSize)) {
    int value;
    while((value = stream.ReadByte()) != -1) {
        buffer.Add((byte) value);
    }
}


Does the following work? For this it would probably be better to change the FileStream to a MemoryStream

fs.Position = 0;
Bitmap bit_map = Bitmap.FromStream(fs) as Bitmap;
bit_map.Save(@"C:\test\test.jpg");

Or

fs.Position = 0;
Image image = Image.FromStream(fs); 
image.Save(@"C:\test\test.jpg", ImageFormat.Jpeg);

Full Example (using your example, but if you want to change how the binary data is read from the other post, that is fine too, just confinue from after you have the buffer):

byte[] buffer = new byte[Request.ContentLength];
using (BinaryReader br = new BinaryReader(Request.InputStream))
    br.Read(buffer, 0, buffer.Length);
MemoryStream mem_stream = new MemoryStream (buffer); 
mem_stream.Write(buffer, 0, buffer.Length); 
mem_stream.Position = 0;
Image image = Image.FromStream(mem_stream); 
image.Save(@"C:\test\test.jpg", ImageFormat.Jpeg);
mem_stream.Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜