ASP.NET MVC上传图片 [英] ASP.NET MVC upload image

查看:187
本文介绍了ASP.NET MVC上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发现了一些code要做到这一点,并试图落实到我的项目,但到目前为止,它一直未果。我没有得到任何错误,但我没有看到任何图像存储在我的图片在Visual Studio中的目录。

查看:

  @using(Html.BeginForm())
{
    <跨度>请在此输入你的故事:其中; / SPAN>
    < textarea的ID =告别赛NAME =告别赛>< / textarea的>
    <按钮式=提交>提交< /按钮>
    <输入类型=文件名称=文件/>
}

控制器:

  [HttpPost]
    公众的ActionResult创建(褒奖褒奖)
    {
        如果(Request.Files.Count大于0)
        {
            var文件= Request.Files [0];            如果(文件= NULL&放大器;!&安培; file.ContentLength大于0)
            {
                变种文件名= Path.GetFileName(file.FileName);
                VAR路径= Path.Combine(使用Server.Mappath(〜/图片/),文件名);
                file.SaveAs(路径);
            }
        }
        TestimonialsContext的TestContext =新TestimonialsContext();
        testContext.testimonialContext.Add(推荐);
        testContext.SaveChanges();
        返回RedirectToAction(「指数」);
    }

下面,如果块正常工作的一部分。这只是保存一个textarea的数据库的内容。有什么想法吗?我需要对我的模型的任何变化?

模型:

  [表(推荐)]
公共类推荐
{
    公众诠释标识{搞定;组; }
    公共字符串见证{搞定;组; }
}

上下文类:

 公共类TestimonialsContext:的DbContext
{
    公共DbSet<谈> testimonialContext {搞定;组; }
}


解决方案

您文件不被公布,因为你没有在表格上的必要是enctype 属性。更改视图中使用

  @using(Html.BeginForm(创建,推荐,FormMethod.Post,新{ENCTYPE =的multipart / form-data的}))

您现在将得到的文件,并保存它,但你的推荐对象没有关系,所以你不能恢复。你需要在你的推荐表添加其他字段来存储文件属性(或单独的表,如果一个推荐可以有多个图像)。我还建议你将文件保存到你的服务器的唯一标识符(如的Guid 来prevent意外覆写,如果用户上传的文件具有相同的名称)。您修改后的模型可能是

 公共类推荐
{
    公众诠释标识{搞定;组; }
    公共字符串见证{搞定;组; }
    公共字符串的ImagePath {搞定;组; }
    公共字符串ImageDisplayName {搞定;组; }
}

我也建议使用包括上述性能视图的视图模型加上公共HttpPostedFileBase图片{搞定;组; } ,这样就可以强烈地绑定到模型,并添加验证属性(例如 [文件大小] 属性假设你不想让用户上传2GB的文件)。然后,您的控制器的方法是

  [HttpPost]
公众的ActionResult创建(TestimonialVM模型)
{
    // ModelState.IsValid检查省略
    褒奖褒奖=新褒奖();
    //地图视图模型属性数据模型
    ....
    如果(model.Image =空&放大器;!&放大器; model.Image.ContentLength大于0)
    {
        字符串显示名= model.Image.FileName;
        字符串fileExtension = Path.GetExtension(显示名);
        字符串文件名=的String.Format({0}。{1},Guid.NewGuid(),fileExtension)
        字符串路径= Path.Combine(使用Server.Mappath(〜/图片/),文件名)
        model.Image.SaveAs(路径);
        //更新数据模型
        testimonials.ImagePath =路径;
        testimonials.ImageDisplayName =显示名;
    }
    TestimonialsContext的TestContext =新TestimonialsContext();
    testContext.testimonialContext.Add(推荐);
    testContext.SaveChanges();
    返回RedirectToAction(「指数」);
}

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; }
}

解决方案

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

这篇关于ASP.NET MVC上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆