2016-01-06 59 views
-2

我有一种方法可以上传我的解决方案的标准文件。但是,我无法找到如何将文件传递给另一种方法。将Var传递给MVC中的文件上传方法

这里是我的代码:

var file = Request.Files[0]; 

if (file != null && file.ContentLength > 0) 
{ 
     _fileName = new FileController().UploadFile(file, "Tickets", ticketReturn.TicketNumber.ToString()); 
} 



public string UploadFile(File file, string SubPath, string folder) 
{ 


     var fileName = Path.GetFileName(file.FileName); 

     string path = ConfigurationManager.AppSettings["MediaFolder"] + "\\" + SubPath + "\\" + fileName; 

     var FullPath = Path.Combine(Server.MapPath("~/Images/"), fileName); 

     file.SaveAs(fullPath); 


     return fileName; 
} 

我遇到的问题是,我不能一个变种传递给方法,所以我想传递一个文件,但是这给了我一个错误,说明不超载方法这些论据。我怎样才能改变它,所以我可以传入文件?

+0

即时在这里猜测'File'参数中的'File'类型是'System.IO.File',这不是你想要的。 –

+0

谢谢@ DanielA.White - 那我想要什么? – djblois

回答

3

您在UploadFile()方法中使用了错误的参数类型。

Request.Files中的项目类型为HttpPostedFileBase而不是File。因此请更新您的方法以使参数具有正确的类型。

public string UploadFile(HttpPostedFileBase file, string SubPath, string folder) 
{ 
    //do something with the file now and return some string 
} 

另外,我不明白为什么要创建您的FileController()的新对象。(你从不同的contorller调用它?)如果这两种方法都在同一个班,你可以简单地调用该方法而不创建新对象。

public ActionResult CreateUserWithImage() 
{ 
    if (Request.Files != null && Request.Files.Count>0) 
    { 
     var f = Request.Files[0]; 
     UploadFile(f,"Some","Abc"); 
    } 
    return Content("Please return something valid here"); 
}  

private string UploadFile(HttpPostedFileBase file, string SubPath, string folder) 
{ 
    //do something with the file now and return some string 
} 

如果要调用从不同的控制器操作此方法,你应该考虑移动这个UploadFile方法不同的公共类(UploadManager.cs?),它可以从任何你想要的控制器使用(您可以通过依赖注入或最坏情况注入它,根据需要在您的控制器中手动创建这个新类的对象)。你不应该从另一个调用一个控制器。

+0

谢谢,Shyju :) – djblois