MVC3 File Input
I am trying to use the html file input to get the path and name of a file. I do not want to upload the file however, and seeing as the files can be quite large, I do not want to pass the file data back to the server either just to get the filename.
Is there a way to bind the file input value to a property in my model, or at least pass just the filename back to the server?
Here is my code:
@using (Html.BeginForm("Upload", "Management", FormMethod.Post , new {enctype="multipart/form-data"})) {
<div>
Upload New Pricing Workbook: <input type="file" name="browse" id="browse" />
</div>
<div>Was Won: @Html.EditorFor(file => file.WasWon)</div&开发者_JAVA百科gt;
<div>
<input type="submit" name="upload" id="upload" value="Upload" />
</div>
}
Is there a way to bind the file input value to a property in my model, or at least pass just the filename back to the server?
You will need javascript for this. You could include a hidden field to your form, and then subscribe for the submit handler of the form and inside this handler set the value of the hidden field from the value of the file input field and clear the value of the file field. Also if you are not interested in uploading the file you don't need the enctype
attribute on the form
$('form').submit(function() {
$('#someHiddenField').val($('#browse').val());
$('#browse').val('');
});
All this being said, for security reasons you cannot get the entire path to the file on the client computer using javascript. You will get only the filename using $('#browse').val()
and that's the best you could hope.
If you want to get paths you could include a standard input field and let the user type it in. This way you will get on the server only what you need (a path to some file).
It should be sufficient to remove the enctype
property of the form and the file name will be populated in your controller action as the upload
string parameter.
Here's a dirty example that should be enough for you to update/tweak to fit your needs:
The Model:
public class HomeModel
{
public string ClientFileName { get; set; }
}
The Controller:
public class homeController : Controller
{
//
// GET: /home/
public ActionResult Index()
{
HomeModel hm = new HomeModel();
if (Request.Form["selectedFilePath"] != null)
hm.ClientFileName = Request.Form["selectedFilePath"];
return View();
}
}
The View:
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function getFileName() {
document.getElementById('selectedFilePath').value = document.getElementById('selectedFile').value;
}
</script>
<form method="post" action="/home/Index">
<input type="file" id="selectedFile" />
<input type="hidden" id="selectedFilePath" name="selectedFilePath" />
<button onclick="getFileName();">
Submit file name</button>
</form>
精彩评论