我正在asp.net中开发一个应用程序,我将上传文件,但是当我使用enctype =“multipart / form-data”时表单集合是空的,当我不使用enctype时,表单集合的名称为上传文件但Request.Files.count = 0.我想获取文件上传以及表单集合中上传文件的名称。任何解决方案?
答案 0 :(得分:1)
使用以下代码查看:
通过以下代码以视图形式添加编码类型:
@using (Html.BeginForm("Create", "Employees", FormMethod.Post,new{ enctype="multipart/form-data"}))
{
@Html.TextBoxFor(model => model.Name)
@Html.TextBoxFor(model => model.Resume, new { type = "file" })
<p>
<input type="submit" value="Save" />
</p>
@Html.ValidationSummary()
}
在控制器的相应操作中添加以下代码,
[HttpPost]
public ActionResult Create(EmployeeViewModel viewModel)
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
string pathFile = string.Empty;
if (file != null)
{
string path = string.Empty;
string fileName = string.Empty;
string fullPath = string.Empty;
path = AppDomain.CurrentDomain.BaseDirectory + "directory where you want to upload file";//here give the directory where you want to save your file
if (!System.IO.Directory.Exists(path))//if path do not exit
{
System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "directory_name/");//if given directory dont exist, it creates with give directory name
}
fileName = Request.Files[file].FileName;
fullPath = Path.Combine(path, fileName);
if (!System.IO.File.Exists(fullPath))
{
if (fileName != null && fileName.Trim().Length > 0)
{
Request.Files[file].SaveAs(fullPath);
}
}
}
}
}
}
我的路径将位于基于目录的目录....你可以给自己想要保存文件的路径
答案 1 :(得分:0)
以下对我来说很好:
@using (Html.BeginForm("someaction", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<button type="submit">Upload</button>
}
请注意,文件输入必须具有name
,稍后将在控制器操作中使用该文件来获取文件。您获得Request.File.Count = 0的事实非常强烈地表明您没有为输入字段提供名称。
和行动:
[HttpPost]
public ActionResult SomeAction(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var filename = Path.GetFileName(file.FileName);
filename = Path.Combine(Server.MapPath("~/uploads"), filename);
file.SaveAs(filename);
}
return View();
}
如果你想使用FormCollection(我不推荐):
[HttpPost]
public ActionResult SomeAction()
{
var file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
var filename = Path.GetFileName(file.FileName);
filename = Path.Combine(Server.MapPath("~/uploads"), filename);
file.SaveAs(filename);
}
return View();
}
您也可以结帐following blog post。
答案 2 :(得分:0)
使用方法:
@Microsoft.Web.Helpers.FileUpload.GetHtml("File", 1, false, false, null, null)
然后在你的控制器中:
public ActionResult YourAction()
{
Request.Files[0]; //Check this out !
}
更多信息:
StackOverFlow:https://stackoverflow.com/a/5060318
Tallan博客:http://blog.tallan.com/2011/02/04/using-mvc3-razor-helpers-and-jcrop-to-upload-and-crop-images/