上传图片的挑战。其他信息正在提交到数据库,但图像未上传

时间:2018-08-02 15:41:37

标签: 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; 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;
    }
}

1 个答案:

答案 0 :(得分:0)

将文件包含在模型中

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>

未映射的属性将确保在db上下文中将其忽略。然后可以使用以下方式访问它:

[HttpPost]
public bool Save(Customer customer) 
{
    if (customer.ImageFile != null)
    {
        // do something
    }
}

将文件保存到数据库不是一个好习惯。而是将其存储在项目目录中,然后将名称或路径的图像存储在数据库中。