Asp.net mvc 5 上传图像的挑战。其他信息正在提交到数据库,但图像未上载

Asp.net mvc 5 上传图像的挑战。其他信息正在提交到数据库,但图像未上载,asp.net-mvc-5,Asp.net Mvc 5,这是客户的类别 namespace test2.Models { public class Customer { public int Id { get; set; } public string Full_Name { get; set; } public Driver Driver { get; set; } [Required] [Display(Name = "Route")] public int DriverId { get;

这是客户的类别

namespace test2.Models
{
  public class Customer
  {
    public int Id { get; set; }
    public string Full_Name { get; set; }
    public Driver Driver { get; set; }

    [Required]
    [Display(Name = "Route")]
    public int DriverId { get; set; }

    [DataType(DataType.ImageUrl)]
    [DisplayName("Driver's License ")]
    public string ImageUrl { get; set; }
  }
}
控制器

[HttpPost]
public ActionResult Save(Customer customer, HttpPostedFileBase file)
{
    if (!ModelState.IsValid)
    {
        var viewModel = new CustomerFormViewModel
        {
            Customer = customer,
            Drivers = _context.Drivers.ToList()
        };

        string imageLocation = "";
        if ((file == null || file.ContentLength < 1))
        {
            ViewBag.Msg = "Please select an image";
            return View();
        }
        if (!SaveImg(file, out imageLocation))
        {
            ViewBag.Msg = "An error occured while saving the image";
        }

        customer.ImageUrl = imageLocation;

        return View("CustomerForm", viewModel);
    }

    //customer.ImageUrl = imageLocation;
    if (customer.Id == 0)
        _context.Customers.Add(customer);
    else
    {
        var customerInDb = _context.Customers.Single(d => d.Id == customer.Id);
        customerInDb.Full_Name = customer.Full_Name;
        customerInDb.DriverId = customer.DriverId;
        customerInDb.ImageUrl = customer.ImageUrl;
    }

    _context.SaveChanges();

    return RedirectToAction("Index", "Customers");
}


public bool SaveImg(HttpPostedFileBase file, out string imageLocation)
{
    imageLocation = "";
    string serverPath = Server.MapPath("~/Images");
    if ((file == null || file.ContentLength < 1))
    {
        //throw an exception showing that no file is present
    }

    var imageString = file.ToString();
    var allowedExtensions = new[]
    {
        ".jpg", ".png", ".jpg", ".jpeg"
    };

    var fileName = Path.GetFileName(file.FileName); //eg myImage.jpg
    var extension = Path.GetExtension(file.FileName);    //eg .jpg

    if (allowedExtensions.Contains(extension.ToLower()))
    {
       string ordinaryFileName = Path.GetFileNameWithoutExtension(file.FileName);
       string myFile = ordinaryFileName + "_" + Guid.NewGuid() + extension;
       var path = Path.Combine(serverPath, myFile);
       file.SaveAs(path);

       string relativePath = "~/Images/" + myFile;
       imageLocation = relativePath;
       return true;
       //return a success message here
    }
    else
    {
       //file save error
       return false;
    }
}
[HttpPost]
公共操作结果保存(客户,HttpPostedFileBase文件)
{
如果(!ModelState.IsValid)
{
var viewModel=新的CustomPerformViewModel
{
客户=客户,
Drivers=\u context.Drivers.ToList()
};
字符串imageLocation=“”;
if((file==null | | file.ContentLength<1))
{
ViewBag.Msg=“请选择图像”;
返回视图();
}
如果(!SaveImg(文件,输出图像位置))
{
ViewBag.Msg=“保存图像时出错”;
}
customer.ImageUrl=imageLocation;
返回视图(“CustomPerform”,viewModel);
}
//customer.ImageUrl=imageLocation;
如果(customer.Id==0)
_context.Customers.Add(客户);
其他的
{
var customerInDb=_context.Customers.Single(d=>d.Id==customer.Id);
customerInDb.Full_Name=customer.Full_Name;
customerInDb.DriverId=customer.DriverId;
customerInDb.ImageUrl=customer.ImageUrl;
}
_SaveChanges();
返回操作(“索引”、“客户”);
}
public bool SaveImg(HttpPostedFileBase文件,输出字符串imageLocation)
{
imageLocation=“”;
字符串serverPath=Server.MapPath(“~/Images”);
if((file==null | | file.ContentLength<1))
{
//引发一个异常,显示不存在任何文件
}
var imageString=file.ToString();
var allowedExtensions=new[]
{
.jpg、.png、.jpg、.jpg
};
var fileName=Path.GetFileName(file.fileName);//例如myImage.jpg
var extension=Path.GetExtension(file.FileName);//例如.jpg
if(allowedExtensions.Contains(extension.ToLower()))
{
string ordinaryFileName=Path.getfilenamwithoutextension(file.FileName);
字符串myFile=ordinaryFileName+“”+Guid.NewGuid()+扩展名;
var path=path.Combine(serverPath,myFile);
file.SaveAs(路径);
字符串relativePath=“~/Images/”+myFile;
imageLocation=相对路径;
返回true;
//在此处返回成功消息
}
其他的
{
//文件保存错误
返回false;
}
}

将文件作为模型的一部分包括在内:

public class Customer
{
    public int Id { get; set; }
    public string Full_Name { get; set; }
    public Driver Driver { get; set; }

    [Required]
    [Display(Name = "Route")]
    public int DriverId { get; set; }

    [DataType(DataType.ImageUrl)]
    [DisplayName("Driver's License ")]
    public string ImageUrl { get; set; }

    [NotMapped]
    public HttpPostedFileBase ImageFile { get; set; }
}
视图中的引用如下所示:

@using (Html.BeginForm("Save", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="form-group">
        @Html.TextBoxFor(model => model.ImageFile, new { htmlAttributes = new { @class = "form-control" }, type = "file" })
    </div>

将文件保存到数据库中不是一个好做法。相反,将其存储在项目目录中,并将图像路径的名称或图像存储在数据库中。

对于
文件
,是否获得
NULL
?您的视图代码是什么样子的?
[HttpPost]
public bool Save(Customer customer) 
{
    if (customer.ImageFile != null)
    {
        // do something
    }
}