Unable to cast object of type 'System.Web.HttpInputStream' to type 'System.IO.FileStream' MVC 3

后端 未结 5 844
無奈伤痛
無奈伤痛 2021-02-19 06:37

I have met an issue regarding the casting type from HttpInputStream to FileStream.

How I did ?

I have a HttpPostedFileBase object and I want to have

相关标签:
5条回答
  • 2021-02-19 07:01
    public byte[] LoadUploadedFile(HttpPostedFileBase uploadedFile)
    {
        var buf = new byte[uploadedFile.InputStream.Length];
        uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length);
        return buf;
    }
    
    0 讨论(0)
  • 2021-02-19 07:14

    The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.

    0 讨论(0)
  • 2021-02-19 07:16

    Below code worked for me..

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

    How to create byte array from HttpPostedFile

    0 讨论(0)
  • 2021-02-19 07:17

    I used the following and it worked just fine for the same situation

    MemoryStream streamIWant = new MemoryStream();
    using (Stream mystream = (Stream)AmazonS3Service.GetObjectStream(AWSAlbumBucketName, ObjectId))                                                            
    {
        mystream.CopyTo(streamIWant);
    }
    return streamIWant;
    

    The GetObjectStream returns the same type of string mentioned in the question.

    0 讨论(0)
  • 2021-02-19 07:17

    You can use the .SaveAs method to save the file content. HttpInputSteam probably because it's uploaded through http [browser]

     postedFile.SaveAs("Full Path to file name");
    

    You can also use CopyTo

    FileStream f = new FileStream(fullPath, FileMode.CreateNew);
    postedFile.InputStream.CopyTo(f);
    f.Close();
    
    0 讨论(0)
提交回复
热议问题