C# 从 HttpPostedFileBase 获取文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17877072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:43:33  来源:igfitidea点击:

Getting the file path from HttpPostedFileBase

c#asp.net-mvcfile-uploadfilepathhttppostedfilebase

提问by Traffy

I'm working with ASP.NET MVC 4 and I'm trying to get the path of an uploaded file in order to open and manipulate it. This is how I proceed :

我正在使用 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");
}

View

看法

@{
    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>
    }

When I'm doing that, I get an error which says ... Could not find a part of the path ...

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

How can I get the path where my file is actually located?

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

采纳答案by sky

Can't comment as I don't have enough reputation ... :(

无法评论,因为我没有足够的声誉...... :(

Does the folder ...

文件夹是否...

C:\Users\maab\Desktop\2013-05-10_BuSI Material Project -Last\BuSIMaterial\BuSIMaterial\App_Data\uploads

C:\Users\maab\Desktop\2013-05-10_BuSI Material Project -Last\BuSIMaterial\BuSIMaterial\App_Data\uploads

exist? If not, try to create it manually and try your upload again.

存在?如果没有,请尝试手动创建并再次尝试上传。

回答by shawad

As I understand, you need to upload the file to the server before opening it e.g.

据我了解,您需要在打开文件之前将文件上传到服务器,例如

 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);
    }

I took the above from a similar question's answer by Chance and Darin Dimitrov : File Upload ASP.NET MVC 3.0

我从 Chance 和 Darin Dimitrov 的类似问题的回答中获取了上述内容:文件上传 ASP.NET MVC 3.0

This answer additionally references the usefull blog post Uploading a File (Or Files) With ASP.NET MVC

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