ASP.Net MVC - Read File from HttpPostedFileBase without save

后端 未结 4 1289
醉酒成梦
醉酒成梦 2020-11-29 23:40

I am uploading the file by using file upload option. And i am directly send this file from View to Controller in POST method like,

    [HttpPost]
    public          


        
相关标签:
4条回答
  • 2020-11-30 00:02

    This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here

    You should convert the stream into byte array and then you can read file content

    Please refer following link

    http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]

    Hope this helps

    UPDATE :

    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.

    Taken from here

    // Read bytes from http input stream
    BinaryReader b = new BinaryReader(file.InputStream);
    byte[] binData = b.ReadBytes(file.ContentLength);
    
    string result = System.Text.Encoding.UTF8.GetString(binData);
    
    0 讨论(0)
  • 2020-11-30 00:10

    byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

    0 讨论(0)
  • 2020-11-30 00:15

    An alternative is to use StreamReader.

    public void FunctionName(HttpPostedFileBase file)
    {
        string result = new StreamReader(file.InputStream).ReadToEnd();
    }
    
    0 讨论(0)
  • 2020-11-30 00:20

    A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.

    string result = string.Empty;
    
    using (BinaryReader b = new BinaryReader(file.InputStream))
    {
      byte[] binData = b.ReadBytes(file.ContentLength);
      result = System.Text.Encoding.UTF8.GetString(binData);
    }
    
    0 讨论(0)
提交回复
热议问题