multiple image uploads in mvc3 - asp.net-mvc

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)

Related

Photo Upload Problem in ASP.NET MVC My Blog Project

When I upload a photo, the page just refresh, not upload the photo in ASP.NET MVC My Blog Project. I looked the solution in Stack OverFlow but I didn't handle this problem. I don't know to write which code here because I am firstly trying to make a blog site in ASP.NET. If you are ask to me whatever code, I publish here quickly. Thanks for cooperation.
Say for example your model is
public class blog
{
public int Id { get; set; }
public string Code { get; set; }
public string Photo1 { get; set; }
}
Here I'm storing the photo in the server (Not in the database)
There goes the controller
public ActionResult BeginUploadPhoto(int Id)
{
var Blog= db.blog.Where(a => a.Id == Id).FirstOrDefault();
return View(Blog);
}
public ActionResult UploadPhoto(int? Id, HttpPostedFileBase Logo)
{
BlogCP = db.Blog.Find(Id);
WebImage img = new WebImage(Logo.InputStream);
if (img.Width > 500)
img.Resize(500, 500);
// to reduce the size upon upload
string extension = Path.GetExtension(Logo.FileName);
// get your photo extenstion
string filename = Guid.NewGuid().ToString();
// rename the upload photo
var path = Path.Combine(Server.MapPath("~/BlogPhoto/"), filename + extension);
// make sure that you create a folder BlogPhoto in your project or you can
//name it anything you like
string savepath = "~/BlogPhoto/" + filename + extension;
BlogCP.Photo1= savepath;
img.Save(path);
// save photo in your server
if (ModelState.IsValid)
{
db.Entry(BlogCP ).Property(r => r.Photo1).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index","Staff");
}
return RedirectToAction("Index");
}
There goes the View
#model ProjectName.Entities.Blog
#{
ViewBag.Title = "BeginUploadPhoto";
}
<div class="container">
#if (Model.Photo1 != null)
{
<img id="Preview" class="img-thumbnail" src=#Model.Photo1/>
}
#using (Html.BeginForm("UploadPhoto", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
{
#Html.HiddenFor(m => m.Id)
<div>
<a>Select and upload Photo</a>
<input type="file" id="Logo" name="Logo"
<input type="file" id="Logo" name="Logo" accept="image/*" onchange="loadFile(event)">
</div>
<div class="form-group">
<button id="btnUpload"
class="btn btn-sm btn-primary"
formnovalidate="formnovalidate"
data-pdsa-action="upload">
<i class="glyphicon glyphicon-upload"></i>
Upload
</button>
</div>
}
}

Image upload using #Ajax.BeginForm in .NET MVC?

I want to upload image using Ajax.BeginForm in my application.
Currently HttpPostedFileBase file is getting value 0. Anyone Please guide me here.
I have tried this code but file is not uploading.
Appreciated, if anyone can provide some solutions for this. If I use #Html.BeginForm then It works but I want to use #Ajax.BeginForm.
Model
public class ClsUpload
{
public string FilePath { get; set; }
}
Controller
public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
{
if (Request.Files.Count > 0)
{
file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
model.FilePath = path;
}
}
try
{
UploadDetials details = new UploadDetials();
details.UpdateDetails(model);
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}
Partial View
#model XX.X.Models.File.ClsUpload
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
{
#Html.HiddenFor(model => model.FilePath)
<input type="file" name="file" />
<img src=#Model.FilePath alt="Image" />
<input type="submit" value="Save" />
}
You can update your code with FormMethod.Post, new { enctype = "multipart/form-data" }) and [AcceptVerbs(HttpVerbs.Post)] as follow
In Partial View
#using (Html.BeginForm("ActionMethod1", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
In Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}
This is old, but I want to show how I have accomplished uploading a file using Ajax.BeginForm(). Basically, the overloads will tell you what is possible. I use the overload for: "string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes". Note: I use null for "routeValues".
Here is a code example:
#using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", #id = "NewFileFormID" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
#Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", #id = fileID, onchange = VerifySizeOfFile })
</div>
<div class="col-sm-2">
<button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
</div>
</div>
}

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

MVC 4 Asp.net ,using File Upload code How to save images in Database

here is my view
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File :</td>
<td><input type="file" name="File" id="file" /> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="upload" /></td>
</tr>
Here is my Controller
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Picture picture)
{
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
picture.File.SaveAs(path);
}
return RedirectToAction("Index");
}
and Model:
namespace FileUpload.Models
{
public class Picture
{
public HttpPostedFileBase File { get; set; }
}
This code helps me to save image in my MVC project root Image folder , but I want to save it to my database . I have tried many tutorial but could not succeed yet ... '
I am Actually making the student form every student will register his picture.
Convert your image into bytes and then store it in your database
[HttpPost]
public ActionResult Index(Picture picture)
{
byte[] Image;
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["file"].InputStream))
{
Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
}
Picture.File =Image;
}
return RedirectToAction("Index");
}
Model
public class Picture
{
public byte[] File { get; set; }
}
View For Displaying Image
if (Model.File != null)
{
string imageBase64 = Convert.ToBase64String(Model.File );
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}

how do i refere my textbox of type file from view to controller

Im trying to upload an image to the database but i im getting an error with object refernece not set to an instance of an object.
i have a textbox in the view and im using memorystream in the controller but i cant store the image to the memorystream.
i also have a model where have this property
public HttpPostedFileBase file { get; set; }
heres the code from the view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
#Html.TextBoxFor(m => m.file, new { type = "file" })
#*<input type="file" value="file" />*#
<input type="submit" value="Create" />
</fieldset>
}
and this is the code from the controller:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
var memoryStream = new System.IO.MemoryStream();
file.InputStream.CopyTo(memoryStream);
var fileBytes = memoryStream.ToArray();
return RedirectToAction("Index");
}
add enctype attribute your form element
#using (Html.BeginForm("Create",
"Home",
FormMethod.Post,
new { id = "form", enctype="multipart/form-data" }))
{
}

Resources