仅显示上传的图像

时间:2015-06-25 22:22:33

标签: c# asp.net-mvc

控制器:

[HttpPost]
public ActionResult UploadImage(List<HttpPostedFileBase> files)
{
    EntityDBContext db = new EntityDBContext();
    var imagesShown = db.Images.ToList();

    foreach (var file in files)
    {
        if (file != null)
        {
            string imageName = Path.GetFileName(file.FileName);
            string physicalPath = Server.MapPath("~/Images/" + imageName);
            byte[] pictureAsBytes = new byte[file.ContentLength];

            using (BinaryReader br = new BinaryReader(file.InputStream))
            {
                pictureAsBytes = br.ReadBytes(file.ContentLength);
            }

            //Save to folder
            file.SaveAs(physicalPath);

            //Save new record in database
            Image img = new Image();

            img.ImageName = imageName;
            img.ImageBytes = pictureAsBytes;

            db.Images.Add(img);
            db.SaveChanges();

            //Only show images that user uploaded, not entire database
            imagesShown = imagesShown.Where(x => x.ImageName == imageName).ToList();
        }
        else
        {
            return View("Index");
        }
    }

    return View("ShowImage", imagesShown);
}

查看:

@model IEnumerable<Vidafo.Models.Image>

@foreach(var image in Model)
{
    <img src="data:image; base64, @System.Convert.ToBase64String(image.ImageBytes)" />
}

我试图仅显示用户已使用IQueryable线上传的图片,但这并不好,因为如果该名称已经在数据库中,则会发布所有这些图片。

我只想要显示他们刚刚上传的用户照片。不是整个数据库,我该怎么做?我认为我必须使用&#39; file&#39;不知怎的,但我不确定如何。

1 个答案:

答案 0 :(得分:1)

以下代码段仅导致一次保存并仅返回新上传的图片(我尚未测试您的文件上传代码,因此假设它正常运行):

[HttpPost]
public ActionResult UploadImage(List<HttpPostedFileBase> files)
{
    EntityDBContext db = new EntityDBContext();
    List<Image> uploadedImages = new List<Image>();

    foreach (var file in files)
    {
        if (file != null)
        {
            string imageName = Path.GetFileName(file.FileName);
            string physicalPath = Server.MapPath("~/Images/" + imageName);
            byte[] pictureAsBytes = new byte[file.ContentLength];

            using (BinaryReader br = new BinaryReader(file.InputStream))
            {
                pictureAsBytes = br.ReadBytes(file.ContentLength);
            }

            //Save to folder
            file.SaveAs(physicalPath);

            //Save new record in database
            Image img = new Image
                {
                    ImageName = imageName;
                    ImageBytes = pictureAsBytes;
                };

            uploadedImages.Add(img);
        }
    }
    db.Images.AddRange(uploadedImages);
    db.SaveChanges();
    return View("ShowImage", uploadedImages);
}