Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c# - ASP.NET MVC upload image

I've found some code to do this and tried to implement it into my project, but so far it has been unsuccessful. I don't get any errors, but I don't see any images being stored in my images directory inside visual studio.

View:

  @using (Html.BeginForm())
{
    <span>Please enter your story here:</span>
    <textarea id="testimonial" name="testimonial"></textarea>
    <button type="submit">Submit</button>
    <input type="file" name="file" />
}

Controller:

[HttpPost]
    public ActionResult Create(Testimonials testimonials)
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                file.SaveAs(path);
            }
        }


        TestimonialsContext testContext = new TestimonialsContext();
        testContext.testimonialContext.Add(testimonials);
        testContext.SaveChanges();
        return RedirectToAction("Index");
    }

The part below the if block works fine. That just saves the content of a textarea to the database. Any thoughts? Do I need to make any changes to my model?

model:

[Table("Testimonials")]
public class Testimonials
{
    public int Id { get; set; }
    public string Testimonial { get; set; }
}

context class:

public class TestimonialsContext:DbContext
{
    public DbSet<Testimonials> testimonialContext { get; set; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your file is not being posted because you do not have the necessary enctype attribute on the form. Change the view to use

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

You will now get the file and save it, but there is no relationship to your Testimonials object so you cannot retrieve it. You will need to add additional fields in your Testimonials table to store the file properties (or a separate table if a Testimonials can have multiple images). I also recommend you save the file to your server with a unique identifier (e.g. a Guid to prevent accidental overwriting if 2 users upload files with the same name). You revised model might be

public class Testimonials
{
    public int Id { get; set; }
    public string Testimonial { get; set; }
    public string ImagePath { get; set; }
    public string ImageDisplayName { get; set; }
}

I would also recommend using a view model for the view that includes the above properties plus public HttpPostedFileBase Image { get; set; } so that you can strongly bind to the model and add validation attributes (for example a [FileSize] attribute assuming you do not want to allow users to upload 2GB files). Your controller method would then be

[HttpPost]
public ActionResult Create(TestimonialVM model)
{
    // ModelState.IsValid check omitted
    Testimonials testimonials = new Testimonials();
    // map view model properties to the data model
    ....
    if (model.Image != null && model.Image.ContentLength > 0)
    {
        string displayName = model.Image.FileName;
        string fileExtension = Path.GetExtension(displayName);
        string fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExtension)
        string path = Path.Combine(Server.MapPath("~/Images/"), fileName)
        model.Image.SaveAs(path);
        // Update data model
        testimonials.ImagePath = path;
        testimonials.ImageDisplayName = displayName;
    }
    TestimonialsContext testContext = new TestimonialsContext();
    testContext.testimonialContext.Add(testimonials);
    testContext.SaveChanges();
    return RedirectToAction("Index");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...