对象引用未设置为文件上载系统的对象实例

本文关键字:系统 对象 实例 上载 文件 设置 对象引用 | 更新日期: 2023-09-27 18:28:57

我在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视图: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-catch到您的方法。

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

   // Now perform the rest of the method.
}

在这个控制器方法被点击之前,你应该确保文件已经上传到客户端。