ASP.Net MVC - 读取文件从HttpPostedFileBase不救 [英] ASP.Net MVC - Read File from HttpPostedFileBase without save

查看:2708
本文介绍了ASP.Net MVC - 读取文件从HttpPostedFileBase不救的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用文件上传选项上传文件。而我直接从查看此文件发送到控制器在POST方法一样,

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 ActionResult Page2(FormCollection objCollection)
    {
        HttpPostedFileBase file = Request.Files[0];
    }

假设,我上传一个记事本文件。我如何读取这个文件&功放;追加这个文本字符串生成器,,没有保存该文件....

Assume, i am uploading a notepad file. How do i read this file & append this text to string builder,, without save that file....

我知道关于另存为此文件之后,我们可以看到这个文件。但我怎么读 HttpPostedFileBase 这个文件没有保存?

I'm aware about after SaveAs this file, we can read this file. But How do i read this file from HttpPostedFileBase without save?

推荐答案

这可以通过使用 httpPostedFileBase 类返回的 HttpInputStreamObject 完成按指定的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase%28v=vs.100%29.aspx\">here

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

请参考以下链接

<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.htt$p$pquest.inputstream.aspx\">http://msdn.microsoft.com/en-us/library/system.web.htt$p$pquest.inputstream.aspx]

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

希望这有助于

更新:

这是你从你的HTTP调用获得的流顺序只读
  (非可搜索),并因此FileStream读/写可搜索。你会
  首先需要从HTTP调用整个流读入一个字节
  数组,然后创建从阵列中的FileStream。

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.

从<一个拍摄href=\"http://stackoverflow.com/questions/13119863/unable-to-cast-object-of-type-system-web-httpinputstream-to-type-system-io-fi\">here

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

string result = System.Text.Encoding.UTF8.GetString(binData);

这篇关于ASP.Net MVC - 读取文件从HttpPostedFileBase不救的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆