Reputation: 374
How can i upload a file with additional data in ASP.NET MVC? This is what I have so far:
@using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post))
{
@Html.TextBoxFor(a=>a.SiteNameKey)
<input type="file" name="logo" id="logo" />
<input type="submit" />
}
Action:
[HttpPost]
public ActionResult CreateSiteLogo(SiteSettingsAPIModel siteSetting)
{
// Handle model
}
Model:
public class SiteSettingsAPIModel
{
public int Id { get; set; }
public string SiteNameKey { get; set; }
public byte[] SiteLogo { get; set; }
public string ImageFormat { get; set; }
}
I can only get the value of the input[text] but not the input[file]. I tried using Request.Files[0]
but I'm always getting null.
Upvotes: 1
Views: 2747
Reputation: 126
If you are using file upload in View then you must specify the enctype = "multipart/form-data" in BeginForm
@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" />
}
and in the Controller side,
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();
}
the controller code shall be modified according to your requirement. Hope its helpful
Upvotes: 3
Reputation: 2460
This could help:
@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; }
}
Upvotes: 1