2012-05-01 111 views
39

我有一个上传的形式,我想通过我的信息,如图片和其他一些领域,但我不知道我该怎么上传图片..上传图像

这是我的控制器代码:

[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

什么类型'model.ImageFile'? – Shimmy

+0

@Shimmy:我只是将图像名称保存在数据库中。它是字符串。 –

+0

我最终为每个新图像生成一个GUID并将其名称保存在数据库中。该文件夹不保存到服务器,只是图像文件的名称。该文件夹是动态注入的。 – Shimmy

回答

44

首先,你需要改变你的看法,包括以下内容:

<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

我使用你的代码,我认为它能正常工作,但它显示给我一个错误:访问路径'C:\ Users \ Administrator \ Desktop \ ND \ MyApp \ MyApp \ Uploads'被拒绝。你知道为什么吗 ?为什么它在本地显示给我这个错误? –

+1

嗯,您需要从网站的应用程序池中找到它正在运行的标识(默认情况下这是应用程序池标识)并授予正确的权限。 – mattytommo

+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