在ASP.NET MVC中上传图像

时间:2012-05-01 18:08:18

标签: c# .net asp.net-mvc asp.net-mvc-3 razor

我有一个上传表单,我想传递我的信息,如图片和其他一些字段,但我不知道如何上传图片..

这是我的控制器代码:

[HttpPost]
        public ActionResult Create(tblPortfolio tblportfolio)
        {
            if (ModelState.IsValid)
            {
                db.tblPortfolios.AddObject(tblportfolio);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(tblportfolio);
        }

这是我的观看代码:

@model MyApp.Models.tblPortfolio

<h2>Create</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>tblPortfolio</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ImageFile)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
            @Html.ValidationMessageFor(model => model.ImageFile)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Link)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Link)
            @Html.ValidationMessageFor(model => model.Link)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

现在我不知道如何上传图像并将其保存在服务器上..如何通过Guid.NewGuid();设置图像名称?或者我该如何设置图像路径?

2 个答案:

答案 0 :(得分:45)

首先,您需要更改视图以包含以下内容:

<input type="file" name="file" />

然后,您需要更改帖子ActionMethod以获取HttpPostedFileBase,如下所示:

[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file)
{
    //you can put your existing save code here
    if (file != null && file.ContentLength > 0) 
    {
        //do whatever you want with the file
    }
}

答案 1 :(得分:3)

您可以使用Request收集从Request.Files获取,如果是单个文件上传,只需使用Request.Files[0]从第一个索引中读取:

[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio) 
{
 if(Request.Files.Count > 0)
 {
 HttpPostedFileBase file = Request.Files[0];
 if (file != null) 
 { 
  // business logic here  
 }
 } 
}

如果要上传多个文件,则必须迭代Request.Files集合:

[HttpPost] 
public ActionResult Create(tblPortfolio tblportfolio)
{ 
 for(int i=0; i < Request.Files.Count; i++)
 {
   HttpPostedFileBase file = Request.Files[i];
   if (file != null)
   {
    // Do something here
   }
 }
}

如果您想通过ajax上传没有页面刷新的文件,那么您可以使用this article which uses jquery plugin