file upload with MVC application - asp.net-mvc

I am trying to add file upload to my asp.net mvc4, however, since I am just learning C# I am not sure on how where to add it:
This is the controller:
public ActionResult Create()
{
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View();
}
//
// POST: /Create
[HttpPost]
public ActionResult Create(TotalReport treport)
{
if (ModelState.IsValid)
{
treport.created = DateTime.Now;
db.TotalReports.Add(treport);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View(treport);
}
the view is here:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="mycss">
<input type="file" name="file" />
</div>
</fieldset>
ok here is the part that saves the file:
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = System.IO.Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = System.IO.Path.Combine(Server.MapPath("~/myfolder"), fileName);
file.SaveAs(path);
}

Suppose if your markup is like,
<input type="file" name="file" />
and then your action should look like,
[HttpPost]
public ActionResult(HttpPostedFileBase file)
{
string filename=file.FileName;
filename=DateTime.Now.ToString("YYYY_MM_dddd_hh_mm_ss")+filename;
file.SaveAs("your path"+filename);
return View();
}
here parameter name of HttpPostedFileBase and upload control name should be same. Hope this helps

pick up the files in the controller like so
[HttpPost]
public ActionResult Create(HttpPostedFileBase fileUpload)
{
if (ModelState.IsValid)
{
treport.created = DateTime.Now;
db.TotalReports.Add(treport);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View(treport);
}

just add argument for the posted file to your action :
public ActionResult Create(TotalReport treport, System.Web.HttpPostedFileBase file)
and do whatever you want to do with it - read stream, save it somewhere...

Related

File Upload in asp.net mvc3

I'm currently using Entity Framework Code First approach for my asp.net MVC3(aspx syntax) project.
I have a model in my project called EmployeeModel
public class EmployeeModel
{
public string imageinfo;
public string fileinfo;
}
My DbContext is
public class ContextDB:DbContext
{
public DbSet<EmployeeModel> Employee { get; set; }
}
I would like to have a file browser for both fileinfo and imageinfo in my view to upload the files and images and the path of the files and images need to be stored in the database.
Can anyone please help?
Try using
.chtml
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
Controller :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null) // file here will have your posted file which you post from view
{
int byteCount = file.ContentLength; <---Your file Size or Length
byte[] yourfile = new byte[file.ContentLength];
file.InputStream.Read(yourfile , 0, file.ContentLength);
var doc1 = System.Text.UnicodeEncoding.Default.GetString(empfile);
// now doc1 will have your image in string format and you can save it to database.
}
}
View :
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}

#Html.DisplayFor() value not change after the postback

#Html.DisplayFor() value not change after send data. I read a article about this issue and say it like this; only send data what such as EditorFor, TextBoxFor, TextAreaFor and change state. Is it true? How can I change this value after the postback?
View
#model HRProj.Model.Person
#using(Html.BeginForm("Skills", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m => m.SkillDoc.Filename)
<span class="file-upload">
<span>Choose a file</span>
<input type="file" name="file" />
</span>
File name : #Html.DisplayFor(m => m.SkillDoc.Filename)
<button>Upload</button>
}
Controller
public ActionResult Skills(int? id)
{
Others oparations...
var model = new Person { SkillDoc = db.GetSkillDoc().FirstOrDefault(m => m.PersonId == id) };
return View(model);
}
[HttpPost]
public ActionResult Skills(Person model, HttpPostedFileBase file)
{
Others oparations...
if (ModelState.IsValid)
{
SkillDoc doc = new SkillDoc();
doc.Id = model.SkillDoc.Id;
doc.PersonId = model.SkillDoc.PersonId;
doc.CvDoc = (file != null) ? file.FileName : model.SkillDoc.CvDoc;
db.SkillDocCRUD(doc, "I");
TempData["eState"] = "The record adding successfully";
if (file != null)
{
file.SaveAs(Server.MapPath("~/Files/" + file.FileName));
}
}
return View(model);
}
Please add the following line inside the if block:
model.SkillDoc=doc;
Or rather redirect to Skills action:
return RedirectToAction("Skills", new{id= model.PersonId});

Uploading Files into Database with ASP.NET MVC

I want to give a facility on my form for user to upload files and save in Database.
How is this done in ASP.NET MVC.
What DataType to write in my Model Class. I tried with Byte[], but during the scaffolding the solution could not generate the appropriate HTML for it in the corresponding View.
How are these cases handled?
You could use a byte[] on your model and a HttpPostedFileBase on your view model. For example:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
and then:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
byte[] uploadedFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
// now you could pass the byte array to your model and store wherever
// you intended to store it
return Content("Thanks for uploading the file");
}
}
and finally in your view:
#model MyViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
#Html.LabelFor(x => x.File)
#Html.TextBoxFor(x => x.File, new { type = "file" })
#Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">Upload</button>
}

multiple image uploads in mvc3

If I have situation like below, where I success. handle image upload and store in db. Having this code in mind how would you implement multiple image upload.
Thank you.
So first thing first.
PropertyViewModel.cs
...
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public PropertyViewModel(Property x)
{
....
ImageData = x.ImageData;
ImageMimeType = x.ImageMimeType;
}
public void ToDomainModel(Property x)
{
....
x.ImageData = ImageData;
x.ImageMimeType = ImageMimeType;
}
Now form Create.cshtml razor page
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
}
}
Controller to handle request
[HttpPost]
public ActionResult Create(PropertyViewModel newProperty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
newProperty.ImageMimeType = image.ContentType;
newProperty.ImageData = new byte[image.ContentLength];
image.InputStream.Read(newProperty.ImageData, 0, image.ContentLength);
}
using (session...)
{
using (...begin transaction)
{
MyDomain.Property model = new MyDomain.Property();
newProperty.ToDomainModel(model);
..session save model
.. commiting session
}
}
return RedirectToAction("Index");
}
else
{
return View(newProperty);
}
}
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
}
or if the browser supports HTML5 you could select multiple files in the upload dialog:
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image" multiple="multiple"/>
}
and then:
public ActionResult Create(PropertyViewModel newProperty, IEnumerable<HttpPostedFileBase> image)

Can't convert HttpFileCollectionBase to HttpFileCollection

I have a partial view:
<% using (Html.BeginForm("add", "home", FormMethod.Post,
new { enctype = "multipart/form-data" })){%>
<input name="IncomingFiles" type="file" />
<div class="editor-field"><%: Html.TextBox("TagsInput") %></div>
<p><input type="submit" value="Create" /></p><% } %>
And this in the controller:
[HttpPost]
public ActionResult add(HttpFileCollection IncomingFiles, string TagsInput)
{
return View();
}
It will simply not match up my uploaded file to the HttpFileCollection, they come out as HttpFileCollectionBase.
How can i get the view to pass me a HttpFileCollection?
Do i need any specific BeginForm args?
Thank you!
Do something like this instead on your action side. You don't pass the files as parameters:
[HttpPost]
public ActionResult add(string TagsInput) {
if (Request.Files.Count > 0) {
// for this example; processing just the first file
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength == 0) {
// throw an error here if content length is not > 0
// you'll probably want to do something with file.ContentType and file.FileName
byte[] fileContent = new byte[file.ContentLength];
file.InputStream.Read(fileContent, 0, file.ContentLength);
// fileContent now contains the byte[] of your attachment...
}
}
return View();
}

Resources