C# 将Var传递给MVC中的文件上载方法
我有一个上传文件的方法,这是我的解决方案的标准。但是,我找不到如何将文件传递给其他方法 以下是我的代码:C# 将Var传递给MVC中的文件上载方法,c#,asp.net-mvc,controller,C#,Asp.net Mvc,Controller,我有一个上传文件的方法,这是我的解决方案的标准。但是,我找不到如何将文件传递给其他方法 以下是我的代码: var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { _fileName = new FileController().UploadFile(file, "Tickets", ticketReturn.TicketNumber.ToString()); }
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;
}
我遇到的问题是,我无法将var传递给该方法,因此我尝试传递一个文件,但这给了我一个错误,即没有重载方法具有这些参数。如何更改它以便传入文件?您在
UploadFile()方法中使用了错误的参数类型
Request.Files
集合中的项属于HttpPostedFileBase
类型,而不是文件
。因此,请更新您的方法,使其具有正确的参数类型
public string UploadFile(HttpPostedFileBase file, string SubPath, string folder)
{
//do something with the file now and return some string
}
另外,我不太清楚为什么要为FileController()
创建一个新对象(您是从另一个contorler调用它吗?)。如果两个方法都在同一个类中,您可以只调用该方法而不创建新对象
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
}
如果你从一个不同的控制器动作调用这个方法,你应该考虑把这个上传文件方法移到一个不同的公共类(上载管理器.CS),它可以从你想要的任何控制器中使用(你可以通过依赖注入或最坏情况注入它,根据需要手动创建一个新类的对象在你的控制器中). 您不应该从一个控制器调用另一个控制器。
我猜文件
参数中的文件
类型是System.IO.File
,这不是您想要的。谢谢@DanielA.White-那么我想要什么?