简体   繁体   中英

ASP.NET MVC upload images to a model

I have a little problem with adding images in ASP.NET MVC. I created a folder in my root folder named /Images/Brands/ where I wanted to save images of my brand models.

This is my Brand model:

namespace AspProjectBootstrap.Models
{
    public class Brand
    {
        public int ID { get; set; }
        [Required]
        public String Name { get; set; }
        [Required]
        public String Description { get; set; }
        public virtual ICollection<Product> Products { get; set; }
        public String ImagePath { get; set; }
        [NotMapped]
        public HttpPostedFileBase ImageFile { get; set; }
    }
}

I saw some people saving the path in the models class as ImagePath then when needed get the full path to the images from the ImagesPath .

And this is my create brand function:

public ActionResult Create(Brand brand)
{
    string filename = Path.GetFileName(brand.ImageFile.FileName);
    filename = DateTime.Now.ToString("yymmssfff") + filename+".png";
    brand.ImagePath = "~/Images/Brands/" + filename;
    filename = Path.Combine(Server.MapPath("~/Images"), filename);
    brand.ImageFile.SaveAs(filename);

    if (ModelState.IsValid)
    {
        db.Brands.Add(brand);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(brand);
}

But I get an error.

If you have any idea how to solve this problem, or any other method to do this task.

Thank you in advance.

The error is:

在此处输入图像描述

The create Create.cshtml view is:

<div class="form-group">
    @Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input type="file" name="ImageFile" />
    </div>
</div>

Your Create method is accepting a serialized model, and while the model can contain a file data, chances are it is not resolving the name:

This should work:

@Html.TextBoxFor(model => model.ImageFile, new { type="file" })

This will ensure the resulting input is named so MVC will recognize it on the form submit or serializing the model.

If that isn't working the next thing to check is to put a breakpoint on string filename = Path.GetFileName(brand.ImageFile.FileName); and inspect which part is #null. Is ImageFile null or ImageFile.FileName ? You should also validate your code to check for nulls in case a form can be submitted without supplying a file.

The problem was in the Create.cshtml view:

@using (Html.BeginForm())

The solution was:

@using (Html.BeginForm("Create","Brands", FormMethod.Post, new { enctype = "multipart/form-data" }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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