How to save input type = file field value after failed validation in ASP.NET MVC?

I have a simple form in an MVC application that I made. It contains a file field so that users can upload an image. Everything works great.

The problem is that if the form submission does not pass the verification, the contents of the file field are lost (other fields remain filled, thanks HtmlHelpers!). How to save a file field filled after a failed check?

TIA!

+54
asp.net-mvc forms
Jun 09 '09 at 2:47
source share
7 answers

Browsers are designed this way because of security risks. Cannot set file input field value in HTML or Javascript source. Otherwise, a malicious script could steal some private file without the user's attention.

interesting information about the subject.

+52
Jun 09 '09 at 4:37
source share

As far as I know, you cannot set the value of the input field of an HTML file. I would suggest linking the file input field with a label or text field.

Then you can fill it with the value from the file input field, which will be resent later.

+2
Jun 09 '09 at 3:29
source share

There are flash files for downloading files. Try one of them. Some of them even return to the regular file input box if flash and java script are not supported. I advise you to look for jQuery plugins.

+1
Jan 01 '11 at 8:01
source share

If the file is not too large, you can use base64 and use it as a value for a hidden field.

+1
Dec 03 '14 at 18:52
source share

You cannot set the value of the input field of an HTML file. As a workaround, replace the file upload field with a hidden input field when the form is displayed after validation.

When presenting, you fill in the hidden field with the value from the file entry field (for subsequent re-presentation). Be sure to include the file name or the name of the hidden field at any time (not both):

Note: The code below is for illustration / explanation only. Replace it with the code that matches your language.

<?php /* You may need to sanitize the value of $_POST['file_upload']; * this is just a start */ if(isset($_POST['file_upload']) && !empty($_POST['file_upload'])){ ?> <input type="hidden" name="file_upload" value="<?php print($_POST['file_upload']); ?>" /> <?php } else { ?> <input type="file" name="file_upload" /> <?php } ?> 
0
Jan 16 '15 at 11:42
source share

I would recommend checking in advance through ajax and doing a partial page refresh. In this case, you will not lose the file.

0
May 24 '17 at 15:33
source share

I do not agree with the "impossible", designated as the correct answer. If someone is still looking for an opportunity, here is a job that worked for me. I am using MVC5. The idea is to use a session variable. I got an idea from ASP.Net Form .

My Model / ViewModel (only relevant properties):

 public partial class emp_leaves { public string fileNameOrig { get; set; } public byte[] fileContent { get; set; } public HttpPostedFileBase uploadFile { get; set; } } 

In my controller (HttpPost): // Check

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(emp_leaves emp_leaves) { if (emp_leaves.uploadFile != null && emp_leaves.uploadFile.ContentLength>0 && !string.IsNullOrEmpty(emp_leaves.uploadFile.FileName)) { emp_leaves.fileNameOrig = Path.GetFileName(emp_leaves.uploadFile.FileName); emp_leaves.fileContent = new byte[emp_leaves.uploadFile.ContentLength]; emp_leaves.uploadFile.InputStream.Read(emp_leaves.fileContent, 0, emp_leaves.uploadFile.ContentLength); Session["emp_leaves.uploadFile"] = emp_leaves.uploadFile; //saving the file in session variable here } else if (Session["emp_leaves.uploadFile"] != null) {//if re-submitting after a failed validation you will reach here. emp_leaves.uploadFile = (HttpPostedFileBase)Session["emp_leaves.uploadFile"]; if (emp_leaves.uploadFile != null && emp_leaves.uploadFile.ContentLength>0 && !string.IsNullOrEmpty(emp_leaves.uploadFile.FileName)) { emp_leaves.fileNameOrig = Path.GetFileName(emp_leaves.uploadFile.FileName); emp_leaves.uploadFile.InputStream.Position = 0; emp_leaves.fileContent = new byte[emp_leaves.uploadFile.ContentLength]; emp_leaves.uploadFile.InputStream.Read(emp_leaves.fileContent, 0, emp_leaves.uploadFile.ContentLength); } } //code to save follows here... } 

Finally, in my edit view: here I am conditionally showing a file upload control.

 < script type = "text/javascript" > $("#removefile").on("click", function(e) { if (!confirm('Delete File?')) { e.preventDefault(); return false; } $('#fileNameOrig').val(''); //toggle visibility for concerned div $('#downloadlrfdiv').hide(); $('#uploadlrfdiv').show(); return false; }); < /script> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> @model PPMSWEB.Models.emp_leaves @{ HttpPostedFileBase uploadFileSession = Session["emp_leaves.uploadFile"] == null ? null : (HttpPostedFileBase)Session["emp_leaves.uploadFile"]; } @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="row"> @*irrelevant content removed*@ <div id="downloadlrfdiv" @((!String.IsNullOrEmpty(Model.fileNameOrig) && (Model.uploadFile==n ull || uploadFileSession !=null)) ? "" : "style=display:none;")> <label>Attachment</label> <span> <strong> <a id="downloadlrf" href="@(uploadFileSession != null? "" : Url.Action("DownloadLRF", "emp_leaves", new { empLeaveId = Model.ID }))" class="text-primary ui-button-text-icon-primary" title="Download attached file"> @Model.fileNameOrig </a> </strong> @if (isEditable && !Model.readonlyMode) { @Html.Raw("&nbsp"); <a id="removefile" class="btn text-danger lead"> <strong title="Delete File" class="glyphicon glyphicon-minus-sign"> </strong> </a> } </span> </div> <div id="uploadlrfdiv" @(!(!String.IsNullOrEmpty(Model.fileNameOrig) && Model.uploadFile==n ull) && !Model.readonlyMode ? "" : "style=display:none;")> <label>Upload File</label> @Html.TextBoxFor(model => model.uploadFile, new { @type = "file", @class = "btn btn-default", @title = "Upload file (max 300 KB)" }) @Html.ValidationMessageFor(x => x.uploadFile) </div> </div> } 
0
Oct 24 '17 at 13:23
source share



All Articles