ASP.NET MVC上传图片

时间:2016-03-09 23:35:53

标签: c# asp.net-mvc upload

我找到了一些代码来实现这一点并尝试将其实现到我的项目中,但到目前为止它还没有成功。我没有收到任何错误,但我没有看到任何图像存储在visual studio内的images目录中。

查看:

  @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" />
}

控制器:

[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");
    }

if块下面的部分工作正常。这只是将textarea的内容保存到数据库中。有什么想法吗?我需要对我的模型进行任何更改吗?

模型:

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

上下文类:

public class TestimonialsContext:DbContext
{
    public DbSet<Testimonials> testimonialContext { get; set; }
}

1 个答案:

答案 0 :(得分:4)

由于您在表单上没有必要的enctype属性,因此未发布您的文件。更改视图以使用

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

您现在将获取该文件并保存,但与Testimonials对象没有任何关系,因此您无法检索它。您需要在Testimonials表中添加其他字段以存储文件属性(如果Testimonials可以包含多个图像,则需要单独的表)。我还建议您使用唯一标识符(例如Guid)将文件保存到服务器,以防止2个用户上传具有相同名称的文件时意外覆盖。您修改过的模型可能是

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

我还建议为视图使用视图模型,其中包含上述属性和public HttpPostedFileBase Image { get; set; },以便您可以强烈绑定到模型并添加验证属性(例如假设您的[FileSize]属性不想让用户上传2GB文件)。那么你的控制器方法就是

[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");
}