I’ve this HTML:
<% using (Html.BeginForm("Upload", "BulkUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<%: Html.TextBoxFor(model => model.UploadFile, new { @type = "file" }) %>
<%: Html.ValidationMessageFor(model => model.UploadFile, "*") %>
<%= Html.Button("submit", "Upload", null) %>
<% } %>
And this Model:
public class BulkUploadVM
{
[DisplayName("File to import")]
public HttpPostedFileBase UploadFile { get; set; }
}
And this Controller:
[HttpPost]
public ActionResult Upload(BulkUploadVM model)
{
if (ModelState.IsValid)
{
var stream = model.UploadFile.InputStream;
// Process stream ...
}
return View("Index", model);
}
The upload file is correctly posted to the Controller, but when the Controller returns the View with the model (which has a valid UploadFile), the filepath is empty on the page ?
Is this default behavior ? Or Am I missing something ?
As already described by Oded, it’s not possible to set the value from the file upload input element because of security reasons.
See RFC 1867 and this link.
The file input type creates a field through which users can upload files from their local computer or network. The VALUE attribute specifies the name of the initial file, but it is typically ignored by browsers as a security precaution.