【问题标题】:upload image in folder MVC在文件夹 MVC 中上传图像
【发布时间】:2017-07-06 09:41:48
【问题描述】:

我是 asp.net 的初学者并尝试将图像上传到我的项目图像文件夹中,但它没有将其上传到所需的文件夹中。任何人请给我建议。

创建.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);
}

【问题讨论】:

  • 我在您的Razor code 中看不到任何Submit 按钮。
  • 请看我编辑的问题。

标签: asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

如果文件到达控制器动作并且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 以及相关的内容。

希望对你有帮助!

【讨论】:

  • 请注意,如果 file.FileName 本身就是路径,Path.Combine 将失败,例如C:\Users\USER\Desktop\myFile.jpg。所以我会在file.FileName 周围包裹一个Path.GetFileName()
  • 在上述情况下发布的 file 对象将只包含带扩展名的文件名
  • 我也这么认为。但是有一天,我们像您经常做的那样在 Intranet 中运行了一个应用程序,并使用 IE 访问它。现在 Internet Explorer 有一个特殊区域,它在其中传递整个文件路径而不是名称。我刚刚测试了代码,结果是整个文件路径,看这里:imgur.com/a/5gmPO 几天前我们在这里遇到了这个问题,IFormFile 类:stackoverflow.com/questions/44718080/…
  • 打个断点看看file.SaveAs是否执行无异常
  • @EhsanSajjad 确实保存无异常,但是保存在错误的目录/用相同的内容覆盖上传的文件。
猜你喜欢
  • 2016-08-25
  • 2014-05-02
  • 2020-03-23
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多