我正在使用 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/