c# - 从 HttpPostedFileBase 获取文件路径

标签 c# asp.net-mvc file-upload filepath httppostedfilebase

我正在使用 ASP.NET MVC 4,我正在尝试获取上传文件的路径以便打开和操作它。这就是我进行的方式:

Controller

public ActionResult Bulk(HttpPostedFileBase file)
{
    FileStream fs = System.IO.File.Open(Server.MapPath(file.FileName), 
                                         FileMode.Open, FileAccess.Read);

    return RedirectToAction("Index");
}

查看

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

    @using (Html.BeginForm("Bulk", "Bulk", null, FormMethod.Post, new 
                                          { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

        <fieldset>
            <p>
                <input type="file" name="file"/>
            </p>
            <div class="form-actions">
              <button type="submit" class="btn btn-primary">Create</button>
            </div>
        </fieldset>
    }

当我这样做时,我收到一条错误消息...... Could not find a part of the path ...

如何获取我的文件实际所在的路径?

最佳答案

据我了解,您需要先将文件上传到服务器,然后再打开它,例如

 if (file != null && file.ContentLength > 0) 
    {
        // extract only the fielname
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }

以上内容摘自 Chance 和 Darin Dimitrov 对类似问题的回答 : File Upload ASP.NET MVC 3.0

此答案还引用了有用的博客文章 Uploading a File (Or Files) With ASP.NET MVC

关于c# - 从 HttpPostedFileBase 获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17877072/

相关文章:

c# - Silverlight 中附加和非附加依赖属性之间的区别

jQuery。为什么我不能在文本区域中插入 html img 标签?

ruby-on-rails - Rails 验证错误后如何保留文件上传字段

php - 如何存储非 ASCII 文件名的上传文件?

c# - Lambda 和类型推断

c# - 如何在联系我们页面中发送带有用户电子邮件的电子邮件?

c# - 使用 Goertzel 算法获取频域

c# - 使用NLog获取Application_Start()中的错误并重定向到友好页面错误

c# - 具有键 'XXX' 的 ViewData 项的类型为 'System.Int32' 但必须为 'IEnumerable<SelectListItem>' 类型

ruby - 导轨/ ruby : uploading a binary File and writing it with a File-Object