簡體   English   中英

無法將上傳的圖像轉換為字節數組

[英]unable to convert uploaded image to byte array

我正在嘗試將上傳的圖像轉換為字節數組,以便可以將其存儲在數據庫表中。

以下代碼用於執行從圖像到字節數組的轉換:

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
     BinaryReader reader = new BinaryReader(image.InputStream);
     var imageBytes = reader.ReadBytes((int)image.ContentLength);
     return imageBytes;
}

當我在此代碼上放置斷點以查看返回的圖像時,imageBytes變量顯示{byte [0]}。

下面顯示的代碼是我正在用於上傳該圖像的視圖的控制器中的ActionResult接收操作(當前,我正在使用文件輸入來選擇和上傳圖像):

[HttpPost]
public ActionResult NewsManager(NewsManagerViewModel model)
{
    var newsManagerRepository = new NewsManagerRepository();
    var currentUser = User.Identity.Name;

    if (ModelState.IsValid)
    {
        HttpPostedFileBase file = Request.Files["ImageData"];

        var fileIsImage = file.IsImage();

        if (fileIsImage)
        {
            model.Author = currentUser;

            var newsUploaded = newsManagerRepository.UploadNews(file, model);

            if (newsUploaded == 1)
            {
                return View();
                }

                ModelState.AddModelError("uploadFailed", "News item was not uploaded");

                return View(model);
                }
                ModelState.AddModelError("fileNotImage", "the file you have uploaded is not an image");

                return View(model);
            }

            return View(model);
        }

有誰對我要轉換的圖像為何未成功轉換為字節數組有任何想法?

任何建議將不勝感激,該應用程序當前是MVC 5和.net版本4.5。


調用方法代碼如下:

public int UploadNews(HttpPostedFileBase file, NewsManagerViewModel model)
{
    model.BannerImage = ConvertToBytes(file);
    var ndtms2Utils = new NDTMS2UtilsEntities();

    var news = new News
    {
        Title = model.Title,
        Author = model.Author,
        BannerImage = model.BannerImage,
        DateCreated = DateTime.Now,
        NewsContent = model.NewsContent
    };

    ndtms2Utils.News.Add(news);
    int i = ndtms2Utils.SaveChanges();
    if (i == 1)
    {
        return 1;
    }
    return 0;
}

使用如下所述的convert方法:

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
   return image.InputStream.StreamToByteArray();
}

public static byte[] StreamToByteArray(this Stream input)
{
    input.Position = 0;
    using (var ms = new MemoryStream())
    {
        int length = System.Convert.ToInt32(input.Length);
        input.CopyTo(ms, length);
        return ms.ToArray();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM