如何在ASP.NET MVC中上传包含其他数据的文件? 这就是我到目前为止所做的:
@using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post))
{
@Html.TextBoxFor(a=>a.SiteNameKey)
<input type="file" name="logo" id="logo" />
<input type="submit" />
}
动作:
[HttpPost]
public ActionResult CreateSiteLogo(SiteSettingsAPIModel siteSetting)
{
// Handle model
}
型号:
public class SiteSettingsAPIModel
{
public int Id { get; set; }
public string SiteNameKey { get; set; }
public byte[] SiteLogo { get; set; }
public string ImageFormat { get; set; }
}
我只能获取输入[text]的值,而不能输入[file]。我尝试使用Request.Files[0]
,但我总是变空。
答案 0 :(得分:3)
如果您在View中使用文件上传,则必须在BeginForm中指定enctype =“multipart / form-data”
@using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(a => a.SiteNameKey)
<input type="file" name="logo" id="logo" />
<input type="submit" />
}
并在控制器方面,
public ActionResult CreateSiteLogo(SiteSettingsAPIModel siteSetting, HttpPostedFileBase logo)
{
//Getting the file path
string path = Server.MapPath(logo.FileName);
//getting the file name
string filename = System.IO.Path.GetFileName(logo.FileName);
using (var binaryReader = new BinaryReader(logo.InputStream))
{
fileContent = binaryReader.ReadBytes(logo.ContentLength);
}
siteSetting.SiteLogo = fileContent;
return View();
}
控制器代码应根据您的要求进行修改。希望它有用
答案 1 :(得分:1)
这可能有所帮助:
@model SandBox.Web.Models.SiteSettingsAPIModel
@using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(a => a.SiteNameKey)
<input type="file" name="SiteLogo" id="logo" />
<input type="submit" />
}
public class SiteSettingsAPIModel
{
public int Id { get; set; }
public string SiteNameKey { get; set; }
public HttpPostedFileBase SiteLogo { get; set; }
public string ImageFormat { get; set; }
}