How to create byte array from HttpPostedFile

后端 未结 6 870
广开言路
广开言路 2020-11-29 16:59

I\'m using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array

HttpPostedFile file = context.Reques         


        
相关标签:
6条回答
  • 2020-11-29 17:08
    BinaryReader b = new BinaryReader(file.InputStream);
    byte[] binData = b.ReadBytes(file.InputStream.Length);
    

    line 2 should be replaced with

    byte[] binData = b.ReadBytes(file.ContentLength);
    
    0 讨论(0)
  • 2020-11-29 17:09

    Use a BinaryReader object to return a byte array from the stream like:

    byte[] fileData = null;
    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
    {
        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
    }
    
    0 讨论(0)
  • 2020-11-29 17:11

    before stream.copyto, you must reset stream.position to 0; then it works fine.

    0 讨论(0)
  • 2020-11-29 17:21

    For images if your using Web Pages v2 use the WebImage Class

    var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
    byte[] imgByteArray = webImage.GetBytes();
    
    0 讨论(0)
  • 2020-11-29 17:24

    It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

    Stream stream = file.InputStream;
    stream.Position = 0;
    
    0 讨论(0)
  • 2020-11-29 17:29

    in your question, both buffer and byteArray seem to be byte[]. So:

    ImageElement image = ImageElement.FromBinary(buffer);
    
    0 讨论(0)
提交回复
热议问题