2012-12-26 22 views
1

我想在我的MVC 4.0項目中添加上傳照片功能,請你能告訴我該怎麼做。我正在使用MVC 4.o和照片選項我想給文件/圖像上傳。這裏是我的代碼如何上傳Asp.Net中的照片/圖像4.o項目

@model WebCart.Category 

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

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



{ 
     @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Category</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.Description) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Description) 
      @Html.ValidationMessageFor(model => model.Description) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Photo) 
     </div> 
     <div class="editor-field"> 
      <input name="PhotoFile" id="File" type="file"/> 
     </div> 

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

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 



    [HttpPost] 
      [ValidateInput(false)] 
      public ActionResult Create(Category category) 
      { 
       if (ModelState.IsValid) 
       { 
        db.Categories.AddObject(category); 
        db.SaveChanges(); 
        return RedirectToAction("Index"); 
       } 

       return View(category); 
      } 

回答

1

你的控制器操作可以採取額外的PhotoFile說法:

[HttpPost] 
[ValidateInput(false)] 
public ActionResult Create(Category category, HttpPostedFileBase photoFile) 
{ 
    if (ModelState.IsValid) 
    { 
     // you could manipulate the PhotoFile parameter here 
     // for example let's store the uploaded file to a folder on the server 
     if (photoFile != null && photoFile.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(photoFile.FileName); 
      var path = Path.Combine(Server.MapPath("~/App_Data"), fileName); 
      photoFile.SaveAs(path); 
     } 

     db.Categories.AddObject(category); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(category); 
} 

或者,如果你想閱讀上傳的文件作爲一個字節數組,你可以使用以下命令:

byte[] photo = new byte[photoFile.InputStream.Length]; 
photoFile.InputStream.Read(photo, 0, photo.Length); 
// Now you could assign the byte array to some property of your model 
// and persist it into the database (even if this is a bad practice - 
// it would be more correct to store the photo on the file system and 
// only store the full path to the photo in the database) 

在ASP.NET MVC中上傳文件必須閱讀的文章如下:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx