renaming file uploaded based on its input type's attribute(id) asp.net in mvc - asp.net-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;
});

Related

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 to Get Uploaded File name in Database In MVC 4

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.

File uploading in MVC 4

I simply tried this, but its not working, what is the problem in it,
MY index page:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/from- data" }))
{
<div>
<h1 style="align-content: center; color: blueviolet">Application to upload files</h1>
</div>
<div>
<input type="file" id="file" name="file" />
<br />
<input type="submit" id="load" name="submit" value="Submit" />
</div>
}
And My controller is,
[HttpPost]
public ActionResult Upload()
{
string path = #"~/Content/Upload";
HttpPostedFileBase file = Request.Files["file"];
if (file != null)
file.SaveAs(path + file.FileName);
return Content("Sucess");
}
The path you are attempting to save your file to looks wrong. Try with MapPath:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
string path = Server.MapPath("~/Content/Upload");
if (file != null)
{
file.SaveAs(Path.Combine(path, file.FileName));
}
return Content("Sucess");
}
Also make sure that you have used the correct enctype attribute in your form:
enctype = "multipart/form-data"
instead of:
enctype = "multipart/from- data"

Pass extra parameters along with the HttpPostedFileBase object

In my MVC app, I have an upload View with GET and POST actions.
the question is how can I pass extra data to the POST Action along with the HttpPostedFileBase object, e.g., some ID for example.
You just pass it as an additional parameter
HTML:
<form action="" method="post" enctype="multipart/form-data">
<input type='text' id='txtId' name='id'/>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string id) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

MVC 3 input file always null

I added an input file field but it's always null on the controller. What am I missing?
Here's the code for both my view and controller.
view:
...
#using (Html.BeginForm())
{
...
<input type=file name="file" id="file" class="post-attachment" />
...
}
controller:
[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
// save file to server
if (file != null && file.ContentLength > 0)
{
var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
file.SaveAs(path);
}
...
}
You need to explicitly set the enctype of the form:
#using(Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
You need to change your form to something like -
#using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload"/>
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
There's a load more info (including the sample above) in this question - Html helper for <input type="file" />

Resources