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

查看:29
本文介绍了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....

我知道在 SaveAs 这个文件之后,我们可以读取这个文件.但是如何在不保存的情况下从 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 根据指定的这里

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

请参考以下链接

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.

取自 这里

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

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

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