【问题标题】:How to Upload and Retrieve Images from Entity Framework using mvc4如何使用 mvc4 从实体框架上传和检索图像
【发布时间】:2018-11-20 00:20:13
【问题描述】:

我是 asp.net mvc 的新手。我需要有关如何使用 mvc4 从实体框架上传和检索图像的帮助。请给我一步一步的信息。

这是我的模型

BUser
public byte[] Image { get; set; }

控制器

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            HMSEntities2 db = new HMSEntities2();
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            byte[] y = System.Text.Encoding.UTF8.GetBytes(ImageName);
            string physicalPath = Server.MapPath("~/images/" + ImageName);

            // save image in folder
            file.SaveAs(physicalPath);

            //save new record in database
            User newRecord = new User();

            newRecord.Image = y;

            db.Users.Add(newRecord);

            db.SaveChanges();
        }
        //Display records
        return RedirectToAction("Display","BPatient");
    }

    public ActionResult Display()
    {
        return View();
    }

编辑视图

 @using (Html.BeginForm("FileUpload","BPatient", FormMethod.Post, new{@class = "form-horizontal role='form' container-fluid enctype='multipart/form-data' " }))
<div class="form-group">
 <input type="file" name="file" id="file" style="width: 100%;" />
  <input type="submit" value="Upload" class="submit" />
 </div>

【问题讨论】:

  • 你能告诉我们你的尝试吗?
  • 请看我更新的问题
  • stackoverflow.com/a/20825120/4523071 我正在关注本教程..每当我尝试上传图片时都会出现错误...即(HttpPostedFileBase 文件)为空
  • 你用@using( ... ){ the html here }包围表单?

标签: asp.net-mvc-4


【解决方案1】:

首先,我们不要将图像存储在数据库中,而是对我们图像的引用。

公共类 BUser { 公共 int Id {get;set;} 公共字符串 ImagePath {get;set;} }

现在,在我们的 Action 中,让我们发布图像,将其保存在相关目录中,例如 /Images/UserImages,然后在我们的类中存储对该图像的引用!

所以从这里开始是引用我们将要使用的 ImageService 的 ActionResult:

public ActionResult FileUpload(HttpPostedFileBase file)
{
        if (file.ContentLength > 0 &&     _imageService.IsValidImageType(file.ContentType))
        {
            const string imagePath = "/Images/UserImages/";
            string uploadedImage = _imageService.UploadImage(file, Server.MapPath(imagePath));
            string uploadedPath = string.Format("{0}{1}",imagePath, uploadedImage);

            if (uploadedPath.Contains("Fail"))
            {
                return RedirectToAction("Failed", "BPatient");
            }

            var bUser = new BUser() {Image = uploadedPath};
            //Save to DB
        }

        return RedirectToAction("Display", "BPatient");
}

实际上,我们不想让 Controller 动作变得如此臃肿,但是我试图让它与你已经拥有的相似,所以它不是一个完整的重写。现在这里是我们的服务的代码,它将上传我们的图像,并检查它的图像类型是否有效

//Extract this to a service or helper
        private readonly string[] _validFileTypes = new[] { "image/jpeg", "image/pjpeg", "image/png", "image/gif" };


        public string UploadImage(HttpPostedFileBase file, string path)
        {
            if (file != null)
            {
                try
                {
                    string fileName = System.IO.Path.GetFileName(file.FileName);
                    if (string.IsNullOrEmpty(fileName))
                    {
                        return "Fail";
                    }

                    if (!IsValidImageType(file.ContentType))
                    {
                        return "Fail";
                    }
                }
                catch (Exception ex)
                {
                    return "Fail";
                }

                string extensionlessName = NameWithoutExtesion(file.FileName);
                string randomName = System.IO.Path.GetRandomFileName();
                string pathMain = string.Format("{0}{1}{2}{3}", path, extensionlessName, randomName, System.IO.Path.GetFileName(Path.GetExtension(file.FileName)));
                try
                {
                    file.SaveAs(pathMain);
                    return string.Format("{0}{1}{2}", extensionlessName, randomName, System.IO.Path.GetFileName(Path.GetExtension(file.FileName)));
                }
                catch (Exception ex)
                {
                    return "Fail";
                }
            }
            return "Fail";
        }

这里有两个来自服务的小方法,它们可以减少 UploadImage 的整体大小

        public bool IsValidImageType(string fileType)
        {
            if (string.IsNullOrEmpty(fileType))
            {
                return false;
            }

            if (!_validFileTypes.Contains(fileType))
            {
                return false;
            }
            return true;
        }

        public string NameWithoutExtesion(string name)
        {
            if (!name.Contains("."))
            {
                return name;
            }
            int index = name.LastIndexOf('.');
            string newName = name.Substring(0, index);
            return newName;
        }

这是我可以告诉的有效解决方案。当然,插入数据库需要更多的工作,但是我已经在那里留下了评论让你把代码放进去。

虽然服务可以直接通过复制粘贴操作,但操作需要您做一些工作。一旦一切就绪,我建议您尝试看看有什么不同的做法。

【讨论】:

  • 抱歉@Glitch100 回复晚了...但我在这里收到错误if (file.ContentLength &gt; 0 &amp;&amp; _imageService.IsValidImageType(file.ContentType))string uploadedImage = _imageService.UploadImage(file, Server.MapPath(imagePath)); 错误是名称'_imageService' 在当前上下文中不存在
  • 那是因为我说将所有这些方法添加到一个名为 ImageService 的类中,然后声明它的一个实例以供使用
猜你喜欢
  • 2013-03-17
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 2021-07-26
相关资源
最近更新 更多