我如何添加enctype="multipart/form-data"到使用生成的表单<% Html.BeginForm(); %>?
根据MSDN文档,默认情况下FileExtensionsAttribute(.NET 4.5)应该只允许我上传jpg,jpeg,gif和png文件 - 这就是我想要的.
我尝试上传没有属性的jpg,它可以工作.大.然后我将属性添加到我的视图模型中..
[FileExtensions(ErrorMessage = "Please specify a valid image file (.jpg, .jpeg, .gif or .png)")]
public HttpPostedFileBase ImageFile { get; set; }
Run Code Online (Sandbox Code Playgroud)
没有快乐.验证失败,并显示ErrorMessage.最重要的是,似乎没有办法指定任何允许的自定义文件扩展名.我最终扩展了FileExtensionsAttribute并使用我自己的验证逻辑,它按预期工作.但为什么这种方式不起作用?
如果需要,将发布整个控制器并查看.我使用此示例作为上载逻辑的基础,但使用DataAnnotations.FileExtensionsAttribute而不是Microsoft.Web.Mvc.FileExtensions .. 如何在ASP.NET MVC中上载图像?
我添加了一个输入文件字段,但它在控制器上始终为空。我缺少什么?
这是我的视图和控制器的代码。
看法:
...
@using (Html.BeginForm())
{
...
<input type=file name="file" id="file" class="post-attachment" />
...
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
// save file to server
if (file != null && file.ContentLength > 0)
{
var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
file.SaveAs(path);
}
...
}
Run Code Online (Sandbox Code Playgroud) 在我正在创建的业务应用程序中,我们允许管理员上传包含某些数据的CSV文件,这些数据会被解析并输入到我们的数据库中(正在进行所有适当的错误处理等).
作为升级到.NET 4.5的一部分,我不得不更新此代码的一些方面,并且,当我这样做时,我遇到了一个使用MemoryStream来处理上传文件的人的答案,而不是暂时保存到文件系统.我没有真正的理由要改变(也许它甚至可能不好),但我想尝试一下学习.所以,我快速换掉了这段代码(由于上传其他元数据,从强类型模型中):
HttpPostedFileBase file = model.File;
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
file.SaveAs(path);
CsvParser csvParser = new CsvParser();
Product product = csvParser.Parse(path);
this.repository.Insert(product);
this.repository.Save();
return View("Details", product);
Run Code Online (Sandbox Code Playgroud)
对此:
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
CsvParser csvParser = new CsvParser();
Product product = csvParser.Parse(memoryStream);
this.repository.Insert(product);
this.repository.Save();
return View("Details", product);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我这样做时,事情就会中断 - 我的所有数据都是以空值出现的,而且看起来好像MemoryStream中没有任何内容(尽管我对此并不乐观).我知道这可能是一个很长的镜头,但有什么明显的我在这里缺少或我可以做些什么来更好地调试这个?