【发布时间】:2020-09-13 03:12:10
【问题描述】:
有人可以帮我吗?我一直在关注如何使用 MVC 5 使用文件上传的教程,但文件一直无法上传。
我的 App_Data 文件夹中有一个 Uploads 文件夹,文件应该保存到该文件夹中。在我的控制器中,我有这个:
using System.IO;
namespace [project_name].Controllers
public class [controller_name]: Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
ViewBag.Message = "";
try
{
// Verify that the user selected a file
if (file.ContentLength > 0)
{
// extract only the filename
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);
}
// redirect back to the index action to show the form once again
ViewBag.Message = "File Upload Successful";
return RedirectToAction("Index");
}
catch(Exception ex)
{
ViewBag.Message = ex.Message;
return View();
}
}
}
在我看来,我有这个:
@{
ViewBag.Title = "File Upload";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="col-md-4">
@using (Html.BeginForm("Index", "[controller_name]", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@ViewBag.Message<br />
@Html.TextBox("file", "", new { type = "file" })
<input type="submit" value="Upload" />
}
</div>
</div>
<br />
那么,我错过了什么?这个项目仍在开发中,我使用的是 Visual Studio 2017,所以它仍然使用localhost 进行调试。当我使用断点时,它显示file 仍然是null。我从 catch 块中得到的错误是“对象引用未设置为对象的实例。”。
有人对我在这里做错了什么有任何想法吗?
更新: 我尝试将操作名称更改为:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult UploadFile() { return View(); }
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
ViewBag.Message = "";
try
{
// Verify that the user selected a file
if (file.ContentLength > 0)
{
// extract only the filename
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);
}
// redirect back to the index action to show the form once again
ViewBag.Message = "File Upload Successful";
return RedirectToAction("Index");
}
catch(Exception ex)
{
ViewBag.Message = ex.Message;
return View();
}
}
我添加了视图,但是当我再次尝试时,我遇到了同样的问题。
【问题讨论】:
-
我假设您在本地文件系统上选择了一个有效文件,它没有被使用,并且您具有读取权限。听起来你也成功地调用了你的 POST ActionHandler。请将您的 POST ActionHandler 重命名为“索引”以外的名称。
UploadFile(HttpPostedFileBase file)会很好。如果这有什么不同,请告诉我们。另见:stackoverflow.com/questions/44127682 -
不走运。同样的错误。
-
问:你解决了吗?我猜“不”,我不知道为什么。所以我冒昧地用一个完整的“从头开始”的例子来更新我的帖子。我鼓励您也这样做,然后发回您发现的内容。
标签: file-upload asp.net-mvc-5 visual-studio-2017