2017-07-06 135 views
1

我是asp.net的初學者,並試圖將圖像上載到我的項目Images文件夾中,但未將其上載到所需的文件夾中。有人請給我建議。在文件夾中上傳圖像MVC

Create.cshtml

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

    <div class="form-horizontal"> 
     <h4>lens</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 


     <div class="form-group"> 
      @Html.LabelFor(model => model.lens_img, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       <input type="file" name="file" id="file" style="width: 100%;" /> 
      </div> 
     </div> 
     <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 

    </div> 
} 

Controller.cs

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include = "lens_img")] lens lens, HttpPostedFileBase file) 
{ 
    if (ModelState.IsValid) 
    { 
     if (file != null) 
     { 
      file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/") 
                  + file.FileName); 
      lens.lens_img = file.FileName; 
     } 
     db.lenses.Add(lens); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(lens); 
} 
+0

我在'Razor代碼'中看不到任何'Submit'按鈕。 –

+0

請參閱我編輯的問題。 –

回答

2

如果文件到達控制器動作和file參數不爲空,那麼你應該使用Path.Combine方法生成正確的路徑,不要爲此使用字符串連接,您應該按以下方式嘗試:

file.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Content/Images/"), file.FileName); 

爲了更清楚,讓我們打破兩個步驟:

var mappedPath = HttpContext.Server.MapPath("~/Content/Images/"); 
file.SaveAs(Path.Combine(mappedPath, file.FileName); 

也看看this answer以及它有關。

希望它有幫助!

+0

請注意,如果'file.FileName'本身就是一個路徑,'Path.Combine'將會失敗,例如'C:\用戶\ USER \桌面\ myFile.jpg'。所以我會圍繞'file.FileName'封裝'Path.GetFileName()'。 – jAC

+0

在發佈'文件'對象在上面的情況下,它將只包含擴展名爲文件名 –

+1

我也這麼認爲。但有一天,我們在Intranet上運行了一個應用程序,就像你經常使用IE一樣訪問它。現在Internet Explorer有一個特殊的區域,它在其中傳遞整個文件路徑而不是名稱。我剛剛測試了代碼,結果是整個文件路徑,請參閱:http://imgur.com/a/5gmPO 前幾天,我們在這裏遇到了這個問題,使用'IFormFile'類:https:// stackoverflow .com/questions/44718080/asp-net-core-file-upload-issue/44719038#44719038 – jAC