Upload image and save in database in asp.net mvc3 - asp.net-mvc

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" />
}

Related

How to fire action in the controller when I select a file from an input file control found in edit form

I have a code in editform like this.
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img id="sp" src="/Student/RetrieveImage/model.StudentID" alt="Photo" height=100 width=200 />
<input type="file" name="ImageData" id="ImageData" onchange="DI();"/>
}
And this in Student Controller
HttpPostedFileBase file;
public ActionResult Bind()
{
file = Request.Files["ImageData"];
file = Request.Files["ImageData"];
return RedirectToAction("StudentEdit");
}
The begin form is found in editform which is a partial form. What I need is to fire the Bind Action when file is selected from input file. How can I do this?
You are working with an form(html element) to upload the image(with HTTP POST verb), in your example you have two main options to proceed with the upload:
1'st option: Create a submit input inside the form
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="DI();"/>
<input type="submit" name="submitbutton" value="Upload" />
}
2'nd option: submit the form with javascript, in this example I used the event that you created at the file element:
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="this.form.submit();"/>
}

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.

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;
});

HttpPostedFileBase always return null in ASP.NET MVC

I have a problem when I upload a file in ASP.NET MVC.
My code is below:
View:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
#using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
But uploadFile always returns null.
Can anyone figure out why??
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
#using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="uploadFile"/>
<input type="submit" />
}
you have to provide name to input type file to uploadFile in order to model binding work in ASP.net mvc and also make sure that name of your input type file and argument name of HttpPostedFileBase is identical.
I had tried most of the solutions posted online for this topic, but found it better to use a workaround instead..
It really didn't matter what I did the HttpPostedFileBase and/or HttpPostedFile were always null. Using the HttpContext.Request.Files collection seemed to work with no hassles at all.
e.g.
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(#"\")));
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
In the above example I only grab the first file, but it is just a matter of looping though the collection to save all files.
HTH
Rob
In my scenario the problem was with id attribute, I had this:
<input type="file" name="file1" id="file1" />
The soultion was to remove id:
<input type="file" name="file1" />
While not the answer to this specific user, I would like to point out that HTML requires that the form tag has an enctype attribute with the value multipart/form-data. And of course both the attribute and it's value must be correct.
For mvc, this means that when using beginform, you should use the version with the htmlAttributes parameter
There can be another scenario also. In my case, I was getting this issue because I was directly rendering script tag in my MVC view and IE is giving issue there.
Correct code in view should be as below:
#section scripts
{
<script>
$(document).ready(function () {
$('.fileinput').fileinput();
...
}
You need to use Razor code to set Name of the input file.
<input type="file" name="#Html.Namefor(m => m.propertyName)">

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