简体   繁体   English

从ASP.NET MVC将图像上传到SQL数据库

[英]Upload image to SQL database from ASP.NET MVC

I am trying to upload an image to a SQL database using ASP.NET MVC. 我正在尝试使用ASP.NET MVC将图像上传到SQL数据库。 The database BeforeImage remains as null although I am receiving no error a few file sizes and formats. 尽管我没有收到一些文件大小和格式的错误,但是数据库BeforeImage仍然为null。 Thanks 谢谢

 public class Job
 {
    public int ID { get; set; }
    public byte[] BeforeImage { get; set; }
    public byte[] AfterImage { get; set; }
  }

View model: 查看模型:

public class BeforePhotoVM
{
    public int ID { get; set; }
    public HttpPostedFileBase BeforeImage { get; set; }
}

Get: 得到:

 public ActionResult AddBefore(int? id)
 {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var job = db.Jobs.Find(id);
        var BeforeVM = new BeforePhotoVM();

        //vm = db.Jobs.Find(id);
        return View("Job2", BeforeVM);
}

Post: 帖子:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddBefore([Bind(Include = "ID,BeforeImage")] BeforePhotoVM BeforeVM)
{
    var job = db.Jobs.Find(BeforeVM.ID);

    if (ModelState.IsValid)
    {
       byte[] BeforeImage = new byte[BeforeVM.BeforeImage.InputStream.Length];
       BeforeVM.BeforeImage.InputStream.Read(BeforeImage, 0, BeforeImage.Length);

       job.BeforeImage = BeforeImage;

       db.Entry(job).State = EntityState.Modified;
       db.SaveChanges();

       return RedirectToAction("AddBefore", new { id = job.ID });
    }

    return View("Job");
}

Look, you are doing too many things for something that should be simple. 看,您为简单的事情做了太多的事情。 Plus, next time, post ur html code with ur ajax. 另外,下一次,用ur ajax发布ur html代码。

Let me try to help you. 我来帮你

At your asp.net page. 在您的asp.net页面上。

your Html.Begin form should have the enctype = "multipart/form-data" 您的Html.Begin表单应具有enctype =“ multipart / form-data”

like this 像这样

@using (Ajax.BeginForm("Here goes ur action", "Here goes ur controller", new AjaxOptions { OnSuccess = "something with sucess" }, new { enctype = "multipart/form-data" }))

with that in mind lets got to ur model 考虑到这一点,让我们进入模型

public byte[] Photo { get; set; }

ok ... now lets finish with the controller 好的...现在让我们结束控制器

        public ActionResult Cadastro(YOURMODEL _model, HttpPostedFileBase file)
    {
        _model.Photo = new byte[file.ContentLength];

see, ur controller recives the HttpPostedFileBase and u can access creating a new byte.. but remember.. in ur asp.net code the file name has to be the same in ur controller as it bellow 看到,您的控制器收到了HttpPostedFileBase,您就可以访问创建一个新的字节了。.但是请记住..在您的asp.net代码中,文件名必须与下面的控制器相同

The rest is with u Hope this will help you. 剩下的就是你了,希望这对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM