【发布时间】:2014-12-31 06:47:10
【问题描述】:
我的 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)
感谢您在此问题上提供的任何帮助。
【问题讨论】:
-
如果用户不上传则没有文件,所以你需要chack
file != null -
文件上传没有要选择的文件请用断点检查它可能文件名=null。
标签: c# asp.net-mvc razor file-upload