How to Get Uploaded File name in Database In MVC 4 - asp.net-mvc

I have uploaded file by using this controller
[HttpPost]
public ActionResult Create(AdulLiteracyTeachers adulliteracyteachers, HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.AdulLiteracyTeachers.Add(adulliteracyteachers);
db.SaveChanges();
return RedirectToAction("Index");
}
the view is :
using (Html.BeginForm("Create", "AdultLiteracyTeachers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<label for="file">Upload Image:</label>
<input type="file" name="files" value="" multiple="multiple"/>
<input name="Upload" type="submit" value="Create" />
I want to save the file name in database when i open the specifc record how the picture is generated with name ?

Add a new table, AdultLiteracyTeacherFile
Add a foreign key to the AdulLiteracyTeacher primary key
Check for ModelState.IsValid before saving your files
Save the teacher record first to get its ID
Save each file to disk and then save a new AdultLiteracyTeacherFile for each file, referenced back to the parent teacher file.

Related

unable to get all uploaded file in mvc 5

I have two file upload control with different name and id.
But when i am uploading multiple file ,i am receiving only one file of each control.
Below is my code.
Main View
#using (Ajax.BeginForm("Questionnaire", "Tax", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divQuestionnaire" }, new { id = "formquestionnaire", enctype = "multipart/form-data" }))
{
<div class="clearfix" id="divQuestionnaire">
#{ Html.RenderPartial("_Questionnaire");}
</div>
}
Partial view where file upload control is placed
<input id="PhotoUrl" type="file" class="upload" multiple="multiple" name="PhotoUrl" />
<input id="AddressUrl" type="file" class="upload" multiple="multiple" name="AddressUrl" />
<button type="submit">Save</button>
controller
public ActionResult Questionnaire(HttpPostedFileBase[] PhotoUrl, HttpPostedFileBase[] AddressUrl)
{
}
also tryied this not working
public ActionResult Questionnaire(IEnumerable<HttpPostedFileBase> PhotoUrl, IEnumerable<HttpPostedFileBase> AddressUrl)
{
}

asp.net MVC upload file get null in action's parameter [duplicate]

I'm trying to do my first simple file upload in MVC 5. I'm following a bunch of examples I've found but for some reason in my "Create" ActionResult the uploadFile is always coming in as NULL so the upload code is never running. Anyone see what I might be doing wrong?
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Documents.</h2>
<h4>Upload a new document.</h4>
<div class="well">
#using (Html.BeginForm("Create", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h3>Select a file to upload. </h3>
<input type="file" name="files" value="" multiple="multiple" />
<input type="submit" value="Upload your file" title="Upload" />
<div style="color:Red;font-size:14px">#ViewBag.Message</div>
}
</div>
Here is my controller:
// POST: Documents/Create
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile)
{
try
{
if(uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Server.MapPath("../SiteDocuments" + uploadFile.FileName);
uploadFile.SaveAs(filePath);
}
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View();
}
}
Your file input element's name should match to your action method parameter name.
So update your HTML markup to have the same name attribute value.
<input type="file" name="uploadFile" value="" multiple="multiple" />
and your action method will be
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile)
{
// do something
}
Or change your action method parameter name to match with your file input element name.
<input type="file" name="files" value="" multiple="multiple" />
and your action method will be
[HttpPost]
public ActionResult Create(HttpPostedFileBase files)
{
if(files!= null && files.ContentLength > 0)
{
// do something
}
}
When you add multiple="multiple" attribute to the input element, the browser will allow the end user to select more than one file at a time. In that case If your action method parameter is a single instance of HttpPostedFileBase object, It will receive the first file from the selected n files. If you want all the files, You may change your parameter to a collection such as
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
if (files != null && files.Any())
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
//do something
}
}
}
}

How can I get both a model and HttpPostedFileBase into a controller?

I've looked quite a bit online, and every example I see explains how to get IEnumerable<HttpPostedFileBase> into a controller, OR how to get a model, but not both.
What I want is something like:
<form>
<input type="text" name="Stored file name>
<input type="file" multiple="multiple" name="files>
<input type="submit">
</form>
with controller
[ActionName("Index"), HttpPost]
public ActionResult IndexPost(Models.MyModel mdl, IEnumerable<HttpPostedFileBase> files)
{
// Do some something with the data in mdl and files here
return RedirectToAction("Index");
}
But every way I try to implement this, it comes back 'no parameterless handler found'. It works fine if I don't include the model.
Am I missing something really obvious?
I guess you couldn't find Darin's this post. It's not exactly about passing model with HttpPostedFileBase but if you undrerstand the behavior the it's easy to do that.
See below example.
View
#model WebApplication2.Models.MyModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(m => m.Id)
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Action Method
[HttpPost]
public ActionResult Index(MyModel model, HttpPostedFileBase file)
{
if (file != null)
{
//do your stuff here
}
return View();
}

renaming file uploaded based on its input type's attribute(id) asp.net in mvc

View:
#using (Html.BeginForm("Edit","program","",FormMethod.Post,new {enctype = "multipart/form-data"}))
{
<div class="upload">
<input type="file" name="files" id="EpExpert"/>
<input type="file" name="files" id="EpNewbie"/>
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
Controller:
[HttpPost]
public ActionResult Edit(tr_program program, IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null)
{
//string extension = Path.GetExtension(file.FileName);
string path = AppDomain.CurrentDomain.BaseDirectory + "Documents/Program-PDFs/";
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(path, filename));
}
}
}
uploaded file name should be in file-{id}.pdf
eg: file-EpNewbie.pdf
file-EpExpert.pdf
PLEASE help!!
The id is never sent to the server. You could use the name attribute instead:
#using (Html.BeginForm("Edit", "program", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="upload">
<input type="file" name="EpExpert" />
<input type="file" name="EpNewbie" />
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
and in your controller action:
[HttpPost]
public ActionResult Edit(tr_program program)
{
string location = Server.MapPath("~/Documents/Program-PDFs");
foreach (string name in Request.Files)
{
HttpPostedFileBase file = Request.Files[name];
string filename = string.Format("file-{0}.pdf", name);
filename = Path.Combine(location, filename);
file.SaveAs(filename);
}
...
}
Obviously since you are storing all the files in the same location (~/Documents/Program-PDFs) with the same names (file-EpExpert.pdf and file-EpNewbie.pdf) if 2 users upload different files at the same time they might get overwritten. There seems to be a problem with your design and naming convention but in my answer I illustrated how you could pass the name of the file input to the controller action which could be used to build the resulting filename. Now it's up to you to take this into consideration when building your real application.
You can take an idea from here. Firstly declare id and data-id dynamic. for example
id = '#model.Id' data-id = '#model.Id'
Before submit form, use js or jquery take id value, then post form.
$("#myForm").submit(function () {
var idValue = $(this).attr('data-id');
document.getElementById('yourHiddenValue').value = idValue;
});

Upload image and save in database in asp.net mvc3

I want to add the ability to upload an image and save it in my database. I have a table and one of its columns is an Image data type. I followed this link, and some similar links, but it doesn't seem to work. Here is the code I tried:
if (Request.Files.Count > 0 && Request.Files[0] != null)
{
HttpPostedFileBase file = Request.Files[0];
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), file.FileName);
file.SaveAs(path);
}
But the file doesn't save in the specified folder.
You have to make sure the encType is set to multipart/form-data in the HTML form.
Ex.
#using (Html.BeginForm("Index", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}

Resources