c# - 对象引用未设置为文件上传系统的对象实例

标签 c# asp.net-mvc razor file-upload

我的 MVC 4 应用程序中内置了一个文件上传模块。目前,如果用户选择一个文件并上传,系统工作正常,但如果用户尝试单击提交按钮而没有选择文件,我的应用程序将抛出异​​常。我查看了我的代码,但无法弄清楚是什么原因导致了异常。

这是我正在使用的代码。

FileUploadController 操作:FileUpload:

 // Get the posted file and upload it
    [Authorize]
    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        //throw new Exception("Something went wrong");
        // Get the user ID
        int user_id;
        // Maximum file size 10MB
        //int maxSize = 10485760;
        // Get the maximum size allowed from web.config
        int maxSize = Int32.Parse(ConfigurationManager.AppSettings["MaxFileSize"]);

        user_id = WebSecurity.CurrentUserId;
        if (file.ContentLength > 0 && file.ContentLength < maxSize)
        {
            try
            {
                if (file.ContentLength > 0)
                {

                    var fileName = Path.GetFileName(file.FileName);
                    var fileType = Path.GetExtension(file.FileName);
                    var fileLength = file.ContentLength;

                    var uploadLocation = ConfigurationManager.AppSettings["UploadLocation"];

                    //Response.Write("Length: " + fileLength);
                    //Response.End();

                    switch (fileType.ToString())
                    {
                        // Potential bad extensions
                        // bat exe cmd sh php pl cgi 386 dll com torrent js app jar pif vb vbscript wsf asp cer csr jsp drv sys ade adp bas chm cpl crt csh fxp hlp hta inf ins isp jse htaccess htpasswd ksh lnk mdb mde mdt mdw msc msi msp mst ops pcd prg reg scr sct shb shs url vbe vbs wsc wsf wsh
                        // Block .exe etc  
                        case ".exe":
                        case ".cmd":
                        case ".msi":
                        case ".dll":
                        case ".com":
                        case ".torrent":
                        case ".js":
                        case ".wsh":
                        case ".vbs":
                        case ".asp":
                        case ".cs":
                        case ".vb":
                            ViewBag.Message = "ECTU Secure File Upload - File type not supported: '" + fileType.ToString() + "'";
                            return View();
                        default:
                            // Create a GUID for our stored filename
                            Guid fileGUID = Guid.NewGuid();
                            // Create the file path
                            //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileGUID.ToString());
                            var path = Path.Combine(uploadLocation, fileGUID.ToString());
                            // Upload the file
                            file.SaveAs(path);
                            // Log in DB the file information that has been uploaded
                            int varLogFile = logFileInfo(user_id, fileName, path, fileType, fileGUID.ToString());
                            break;
                    }

                }
                else
                {
                    ViewBag.Message = "ECTU Secure File Upload - No file selected.";
                    return View();
                }
            }
            catch (Exception ex)
            {
                // No file selected
                // Return to view with error message
                ViewBag.Message = ex.ToString(); // "ECTU Secure File Upload - Please select a file to upload.";
                return View();
            }
        }
        else
        {
              ViewBag.Message = "ECTU Secure File Upload - File is too big: " + (file.ContentLength / 1024) + "kb";
              return View();
        }
        //returnto the view with a success message
        ViewBag.Message = "ECTU Secure File Upload - Upload Successful: " + file.FileName;
        return View();
    }

Razor html View :FileUpload.cshtml

@{
ViewBag.Title = "FileUpload";
}

<hgroup class="title">
    <h1>@ViewBag.Message</h1>
</hgroup>

<article>
<br />
<form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="file" id="file" />
  <input type="submit" formaction="FileUpload" value="Submit">
</form>


<p><span class="instructions">Instructions: </span> Select a file to upload. Please note that executable (.exe) files are not supported. All files must be less than 1.9 Gb. Please refer to the user guide for more information.</p>

<p>@Html.ActionLink("Back to List", "Uploader", "Upload")</p>
</article>

这是完整的错误代码和堆栈跟踪:

Object reference not set to an instance of an object.
System.Web.HttpException (0x80004005): A public action method 'Uploadermvc error Object reference not set to an instance of an object' was not found on controller 'SecureFileUploadTraining.Controllers.UploadController'.

   at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)

   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)

   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)

   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)

   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

感谢您就此问题提供的任何帮助。

最佳答案

虽然这些人已经回答了,但您应该在您的方法中实现一个 if-then-now 捕获。

public ActionResult FileUpload(HttpPostedFileBase file)
{
   if(file == null)
   throw new ArgumentException("file")


   // Now perform the rest of the method.

}

您应该确保文件已在客户端上传,在此 Controller 方法被调用之前。

关于c# - 对象引用未设置为文件上传系统的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26734122/

相关文章:

c# - 什么可能导致 System.Net 错误 :AcquireCredentialsHandle() failed with error 0X8009030D?

c# - 将 wav 文件存储在数组中

asp.net-mvc - 如何访问请求上下文中 MvcApplication 类的实例属性?

javascript - 如何将 View (cshtml) 加载到 iframe 中?

c# - 提交后填充表单字段 ASP.NET Core 3.1 MVC

c# - 将帮助图标添加到 WinForms 表单标题栏

java - 球围绕 3D 球体运动

c# - 防伪 token 问题已解决但对项目产生影响后很奇怪

asp.net-mvc - ASP.NET MVC - 使用 Moq 框架对 RenderPartialViewToString() 进行单元测试?

javascript - 动态二维数组,JavaScript 和 Razor 语法错误