【问题标题】:MVC 5 file uploadMVC 5 文件上传
【发布时间】: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


【解决方案1】:

您尝试这样做应该相当简单,而且我认为您已经掌握了所需的所有信息。对不起,如果不是这样:(

如果您的问题没有解决,我鼓励您开始一个“hello world”项目,“从头开始”,如下所示:

  1. 创建项目:

    MSVS > 新项目 > 名称= 简单上传 > MVC=是的

  2. 添加控制器:

    控制器 > 添加 > 添加控制器 > MVC 5 控制器 - 空 > 名称= UploadController

    public const string UPLOADS_FOLDER = @"c:\temp";
    public ActionResult Index() { ... }
    [HttpGet] public ActionResult UploadFile() { ... }
    [HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) { ... }
    
  3. 添加视图:

    视图 > 添加 > 添加视图 > Name= UploadFile, Template= Empty, Use a layout page= Y

  4. Windows 资源管理器:

    确保“上传文件夹”存在

  5. MSVS:

    启动应用,浏览到 http://localhost:58021/Upload/UploadFile

控制器\UploadController.cs

using System.IO;
using System.Web;
using System.Web.Mvc;

namespace SimpleUpload.Controllers
{
    public class UploadController : Controller
    {
        public const string UPLOADS_FOLDER = @"c:\temp";

        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(file.FileName);
                    string path = Path.Combine(UPLOADS_FOLDER, fileName);
                    file.SaveAs(path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }

        }
    }
}

视图\上传\UploadFile.cshtml

@{
    ViewBag.Title = "UploadFile"; 
 }

<h2>@ViewBag.Title</h2> 
@using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
 }

【讨论】:

  • 还是没有运气。现在我收到以下服务器错误:找不到资源。说明:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。请求的 URL:/HROFileUpload/Index 版本信息:Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.8.4210.0 和 URL 读取:“localhost:44399/HROFileUpload/Index?”
  • 我将在今天晚些时候讨论这个问题,并告诉你进展如何。非常感谢您的耐心和愿意提供帮助的意愿!
  • 我创建了一个新项目并按照您提供的链接中的说明进行操作,中提琴效果很好。所以现在的问题是,为什么它不能在我的项目中使用 @using Html.BeginForm() 。谢谢你的帮助,我今天会深入研究一下,看看我想出了什么。当我找到可行的解决方案时,我会发布更新。
  • 很高兴你能成功!请记住,从我们之前的讨论中,按照惯例,“索引”这个名称是“特殊的”。具体来说,控制器中的Index() 方法将由对http:&lt;port&gt;//myurl/ 的HTTP“GET”请求调用。显式尾随“/”或隐式http:&lt;port&gt;//myurl。这可能(或可能不)与您的故障排除有关...
猜你喜欢
  • 1970-01-01
  • 2014-05-02
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多