无法将 HttpPostedFileBase 转换为 byte[]

本文关键字:byte 转换 HttpPostedFileBase | 更新日期: 2023-09-27 18:33:30

我有一个控制器,可以接收HttpPostedFileBase(.jpg或.png等(。

public ActionResult SaveImage(HttpPostedFileBase ImageData)
{
  //code
}

ImageData成为具有以下属性的System.Web.HttpPostedFileWrapper对象:

ContentLength: 71945
ContentType: "image/png"
FileName: "foo.png"
InputStream: {System.Web.HttpInputStream}

我将 ImageData 转换为图像,然后将图像转换为 byte[] 然后转换为 base64 字符串没有任何问题 - 但我尝试使用以下代码将其直接转换为 byte[]:

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

memoryStream在调用 imgData = memoryStream.ToArray(); 时始终为空,因此imgData最终也为 null。

很难理解为什么我不能将此输入流读入内存流。输入流似乎很好,除了 readTimeout 和 writeTimeout 属性抛出timeouts are not supported on this stream 。 我做错了什么,为什么我不能将图像数据转换为字节[]?

以防万一,这是我的 AJAX 调用。可能是将contentTypeprocessData选项设置为 false 的问题吗?

$.ajax({
    url: 'SaveImage',
    data: formData,
    type: "POST",
    contentType: false,
    processData: false,
    beforeSend: function () {
        $("#loadingScreenModal").modal('toggle');
    },
    success: function (data) {
        // etc.
    }
});

更新:我通过将HttpPostedFileBase转换为Image,然后将Image转换为byte[]来解决问题,但我仍然有兴趣弄清楚为什么我必须执行这个中间步骤。

Image i = Image.FromStream(ImageData.InputStream, true, true);
byte[] imgData = imageToByteArray(thumb);
public byte[] imageToByteArray(Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

更新#2:我认为我的代码的问题可能是if (memoryStream == null)块中的代码从未被调用。

无法将 HttpPostedFileBase 转换为 byte[]

您可以使用 BinaryReader 类将字符串读入字节数组:

byte[] imgData;
using (var reader = new BinaryReader(ImageData.InputStream))
{
    imgData = reader.ReadBytes(ImageData.ContentLength);
}

我有类似的代码,其中我直接将流读入一个字节[],如下所示:

var streamLength = ImageData.InputStream.Length;
var imageBytes = new byte[streamLength];
ImageData.InputStream.Read(imageBytes, 0, imageBytes.Length);

然后,我将 imageBytes 作为varbinary(MAX)存储到数据库中。似乎工作正常。

答案最终是memoryStream == null检查,正如JoeEnos所建议的那样。 MemoryStream在此检查正上方的行上实例化 - 因此它不应为 null - 而应改为使用 if (memoryStream.Length == 0) 进行检查。

模型代码

public class AdminDetailsModel
{
    public byte[] AdminImage { get; set; }
 }

查看代码

@using (Html.BeginForm("Create", "AdminDetails", FormMethod.Post, new { enctype = "multipart/form-data" }))
{   
    <div class="form-group">
        @Html.LabelFor(model => model.AdminImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="ImageData" id="ImageData" />                              
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

控制器中的类似代码

public ActionResult Create(AdminDetailsModel viewmodel)
{
    if (ModelState.IsValid)
    {
    HttpPostedFileBase file = Request.Files["ImageData"];
    viewmodel.Image = ConvertToByte(file);
    db.YourDbContextSet.Add(viewmodel);
    db.SaveChanges();
    }
}
public byte[] ConvertToByte(HttpPostedFileBase file)
    {
        byte[] imageByte = null;
        BinaryReader rdr = new BinaryReader(file.InputStream);
        imageByte = rdr.ReadBytes((int)file.ContentLength);
        return imageByte;
    }

希望这会有所帮助