将 HttpPostedFileBase 转换为 byte[] [英] Convert HttpPostedFileBase to byte[]

查看:56
本文介绍了将 HttpPostedFileBase 转换为 byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 MVC 应用程序中,我使用以下代码上传文件.

In my MVC application, I am using following code to upload a file.

模型

 public HttpPostedFileBase File { get; set; }

查看

@Html.TextBoxFor(m => m.File, new { type = "file" })

一切正常..但我正在尝试将结果字段转换为字节[].我该怎么做

Everything working fine .. But I am trying to convert the result fiel to byte[] .How can i do this

控制器

 public ActionResult ManagePhotos(ManagePhotos model)
    {
        if (ModelState.IsValid)
        {
            byte[] image = model.File; //Its not working .How can convert this to byte array
        }
     }

推荐答案

正如 Darin 所说,您可以从输入流中读取 - 但我会避免依赖所有数据一次性可用.如果您使用的是 .NET 4,这很简单:

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

如果需要,可以很容易地在 .NET 3.5 中编写与 CopyTo 等效的代码.重要的部分是您从 HttpPostedFileBase 中读取.输入流.

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

出于高效目的,您可以检查返回的流是否已经是MemoryStream:

For efficient purposes you could check whether the stream returned is already a MemoryStream:

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

这篇关于将 HttpPostedFileBase 转换为 byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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