我在ASP.NET MVC 3中出错以便上传文件

时间:2011-01-13 16:30:21

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

我有一个简单的文件上传示例,我在ASP.NET 1中制作,2在razor中工作3,它不起作用

使用此代码上传文件不能用于3甚至工作1或MVC 2版本

 HttpPostedFileBase file = Request.Files["file"];
            if (file.ContentLength > 0) // accept the file 
            {
                string filename = Server.MapPath("~" + "/upload/" + file.FileName);
                file.SaveAs(filename);
            }
            ViewBag.filelocate = "/upload/" + file.FileName;
            return View();

是他们在asp.net MVC 3中将我的应用程序的上传文件夹中的文件上传的任何方式

Server Error in '/' Application.
--------------------------------------------------------------------------------

The given path's format is not supported. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NotSupportedException: The given path's format is not supported.

Source Error: 


Line 20:             if (file.ContentLength > 0) // accept the file 
Line 21:             {
Line 22:                 string filename = Server.MapPath("~" + "/upload/" + file.FileName);
Line 23:                 file.SaveAs(filename);
Line 24:             }


Source File: C:\Users\steven\Desktop\Web Design\File Upload\FileUpload\Controllers\HomeController.cs    Line: 22 

2 个答案:

答案 0 :(得分:2)

我认为这是浏览器发送完整文件路径的问题 试试这个:

if (file.ContentLength > 0)
{ 
 string filename = Server.MapPath("~" + "/upload/" + System.IO.Path.GetFilename(file.FileName)); 
 file.SaveAs(filename); Line 24:             
} 

答案 1 :(得分:1)

您确定在HTML表单上指定了正确的MIME类型吗?它必须是“multipart / form-data”