我创建了一个保存文件的 Controller 。
以下代码是该 Controller 的一部分:
if ( Request.Files.Count != 0 ) {
HttpFileCollectionBase files = Request.Files;
foreach ( HttpPostedFileBase file in files ) {
if ( file.ContentLength > 0 ) {
if ( !file.ContentType.Equals( "image/vnd.dwg" ) ) {
return RedirectToAction( "List" );
}
}
}
}
在 ASPX 页面中很简单:
<input type="file" name="file" />
<input type="file" name="file" />
...// many inputs type file
问题出在 foreach
上,因为它会返回如下错误(我知道是因为我在 Debug模式下运行并在 foreach 语句处放置了断点):
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFileBase'.
我的错误是什么?
最佳答案
像这样尝试:
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files != null && files.Count() > 0)
{
foreach (var uploadedFile in files)
{
if (uploadedFile.ContentType != "image/vnd.dwg")
{
return RedirectToAction("List");
}
var appData = Server.MapPath("~/app_data");
var filename = Path.Combine(appData, Path.GetFileName(uploadedFile.FileName));
uploadedFile.SaveAs(filename);
}
}
return RedirectToAction("Success");
}
并修改标记,使文件输入命名为文件:
<input type="file" name="files" />
<input type="file" name="files" />
...// many inputs type file
关于c# - 使用 C# 和 MVC3 的 HttpFileCollectionBase 问题上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500550/