2017-07-06 226 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