I am trying to check if the file is selected in the fileupload in mvc using Form collection but the formvalues is always null , fileupload is not passing the uploaded file name to formcollection , below is the code:
public ActionResult Create(FormCollection formValues,IEnumerable<HttpPostedFileBase> files, Venue venue)
{
string[] images = { "", "" };
int i = 0;
// string smallImage;
// string largeImage;
foreach (HttpPostedFileBase file in files)
{
if (file != null)
{
if (i == 0)
{
string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
file.SaveAs(path);
Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 162, 105);
images[0] = newFileName;
venue.ImageSmall = images[0];
// smallImage = "selected";
}
if (i == 1)
{
string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
file.SaveAs(path);
Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 212, 240);
images[1] = newFileName;
venue.ImageLarge = images[1];
// largeImage = "selected";
}
}
i++;
}
if (string.IsNullOrEmpty(formValues["files1"]) || string.IsNullOrEmpty(formValues["files2"]) )
{
ModelState.AddModelError("files", "Please upload a file");
}
<td>
<div class="editor-field">
<input type="file" name="files" id="files1" style="color:White" />
</div>
</td>
</tr>
<tr>
<td>
Detail Image
</td>
<td>
<div class="editor-field">
<input type="file" name="files" id="files2" style="color:White"/>
</div>
</td>
</tr>
![In the keys section there is no formvalue["files"]](https://i.sstatic.net/ZzasH.jpg)
You are using wrong IDs ("files1" and "files2" in html, but "file1" and "file2" in the code)
Even if you used correct IDs, this code wouldn't work because form parameters are named using values from "name" attribute. So, you have to create an unique name for each input tag in your html and then use these names in code.
In case you want to loop over files. You can give them the same id and then use Request.Files property in controller method on server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With