加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.Net MVC – 从HttpPostedFileBase读取文件,而不保存

发布时间:2020-12-15 19:33:46 所属栏目:asp.Net 来源:网络整理
导读:我使用文件上传选项上传文件。我直接发送这个文件从View到控制器在POST方法like, [HttpPost] public ActionResult Page2(FormCollection objCollection) { HttpPostedFileBase file = Request.Files[0]; } 假设,我上传一个记事本文件。如何读取此文件将此
我使用文件上传选项上传文件。我直接发送这个文件从View到控制器在POST方法like,
[HttpPost]
    public ActionResult Page2(FormCollection objCollection)
    {
        HttpPostedFileBase file = Request.Files[0];
    }

假设,我上传一个记事本文件。如何读取此文件&将此文本附加到字符串构建器,而不保存该文件….

我知道后SaveAs这个文件,我们可以读这个文件。但是如何读取这个文件从HttpPostedFileBase没有保存?

解决方法

这可以使用httpPostedFileBase类返回HttpInputStreamObject根据指定的 here

您应该将流转换为字节数组,然后您可以读取文件内容

请参考以下链接

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

希望这可以帮助

更新:

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.

摘自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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读