Can Image be uploaded with pure bootstrap 3 in .NET MVC application? - asp.net-mvc

I want to upload image in my application without use of any JavaScript. I am new to .NET MVC development.
This is Edit View where I want to change the different image from local machine.
I am not sure whether it is possible or not. Anyone Please guide me here.
I have tried this code but file is not uploading.
#model XX.X.Models.File.ClsUpload
#Html.HiddenFor(model => model.FilePath)
<input type='file'/>
<img src=#Model.FilePath alt="Image" />
<input type="submit" value="Save" />

Using this code with .Net MVC i am saving employees pic you can try this code withOut javascript
View Code
#using (Html.BeginForm("Create", "Employees", FormMethod.Post, new { enctype =
"multipart/form-data" }))
{
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input id="AttachmentName" name="AttachmentName" type="file">
</div>
</div>
</div>
}
Controller code
[HttpPost]
public ActionResult Create(EmployeeClass employeeClass, HttpPostedFileBase AttachmentName)
{
string newProfileName = "";
if (AttachmentName != null)
{
HttpPostedFileBase AttachmentNameFile = Request.Files["AttachmentName"];
string productImageExt = Path.GetExtension(AttachmentNameFile.FileName);
newProfileName = DateTime.Now.ToString("MMddyyHHmmss") + productImageExt;
var saveimage = SaveImage(AttachmentNameFile, newProfileName);
}
}
public bool SaveImage(HttpPostedFileBase AttachmentNameFile, string FileName)
{
if (AttachmentNameFile.FileName != "")
{
string folderexist = Server.MapPath("~/images/ProfileImage/");
bool isExist = System.IO.Directory.Exists(folderexist);
if (!isExist)
{
System.IO.Directory.CreateDirectory(folderexist);
}
AttachmentNameFile.SaveAs(folderexist + FileName);
}
return true;
}

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

File upload not working as expected

I am trying to upload a file from my application and it is not working as expected. I am not getting any file into the action method.
I have my viewmodel as below
public class CallQueryViewModel
{
[Display(Name = "Attachment")]
public HttpPostedFileBase UploadFile { get; set; }
}
And my Razor form is as below
#{
var ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "onCallAddBegin",
OnSuccess = "OnCallCreateSuccess",
OnFailure = "OnCallCreateFailure"
};
}
#using (Ajax.BeginForm("AddCall", "CallHandling", ajaxOptions, new { #id = "CallAddForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.UploadFile, new { #class = "col-md-2" })
#Html.TextBoxFor(model => model.UploadFile, new { #class = "col-md-10", type="file" })
</div>
</div>
</div>
<div id="Submit">
<input type="submit" value="Save" class="btn btn-success" />
</div>
}
And my controller action method is as below.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddCall(CallQueryViewModel model)
{
if ((model.UploadFile != null) && (model.UploadFile.ContentLength > 0))
{
// Upload file.
}
}
With the above code, when i am trying to upload the file, I am not receiving any file into the controller action method. The UploadFile is always coming as null.
Could someone suggest what I am missing ?

MVC 5 multiple file upload uploads same file several times

I have built a website using asp.net 4.5 and MVC 5.
In one of my views I want to upload multiple files.
With my code below, the first fileis collected and saved, but it is saved as many times as the number of files I try to upload.
For example:
I choose the files pic1.jpg and pic2.jpg with the file uploader. This results in the file pic1.jpg being saved twice.
While debugging I see that the Request.Files[file]; code returns the same file each time. It seems that I get the same file uploader twice, and that only the first file is selected.
How do I alter my code to fetch all files selected via the uploader?
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProductViewModel product)
{
...
foreach (string file in Request.Files)
{
var hpf = Request.Files[file];
if (hpf != null && hpf.ContentLength > 0)
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
}
...
return RedirectToAction<ProductController>(x => x.Index());
}
View
#model EVRY.OrderCapture.Administration.ViewModels.ProductViewModel
<h2>#Resources.Resources.Create</h2>
#using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
...
<div class="form-group">
<label for="fileUpload" class="control-label col-md-2">Filename:</label>
<div class="col-md-10">
<input type="file" name="files" id="fileUpload" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="#Resources.Resources.Create" class="btn btn-default" />
</div>
</div>
</div>
}
I found the answer to this myself.
I had to select on index instead of name.
for (var i = 0; i < Request.Files.Count; i++)
{
var hpf = Request.Files[i];
if (hpf != null && hpf.ContentLength > 0)
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
}

Uploading image using json in aps mvc

I have a function for uploading selected files into folder in asp mvc4. The code in view page is
<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload">
<input type='file' id="imgInp" accept="image/jpeg"/>
<p>
<input type="submit" value="Upload" class="btn"/>
</p>
</form>
And the controller code is
[HttpPost]
public ActionResult Upload(HttpPostedFileBase imgInp)
{
if (imgInp != null && imgInp.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(imgInp.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName);
imgInp.SaveAs(path);
}
return view("Index");
}
Instead of this i want to send the image from view to controller as Json. Or is there any other methods to upload image without refreshing the view page..?
You can send form using ajax...
<form id="login-form">
<input type="file" name="photo" id="files" accept="image/*;capture=camera">
<button type="submit" onclick="submitform()">Submit</button>
</form>
jquery
function submitform(){
var postdata = $('#login-form').serialize();
var file = document.getElementById('files').files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/Index", false);
xhr.send(fd);
}
controller
[HttpPost]
public JsonResult Index(FormCollection data)
{
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
var Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
}
}
}
uploading file to the server is quite simple. we need is a html form having encoding type set to multipart/form-data and a file input control.
View: NewProduct.cshtml
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>New Product</legend>
<div>
<label>Product Name:</label>
#Html.TextBoxFor(x => x.ProductName)
</div>
<div>
<label>Product Image:</label>
<input name="photo" id="photo" type="file">
</div>
<div>
#Html.ValidationSummary()
</div>
<input type="submit" value="Save" />
</fieldset>
</form>
The uploaded files are available in HttpFileCollectionBase of Request.Files.
controller:
[HttpPost]
public ActionResult NewProduct()
{
HttpPostedFileBase image = Request.Files["photo"];
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var fileName = Path.GetFileName(image.FileName);
string subPath = Server.MapPath("ProductLogo");
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
var path = Path.Combine(subPath+"\\", fileName);
if (System.IO.File.Exists(path))
{
var nfile = DateTime.Now.ToString() + "_" + fileName;
path = Path.Combine(subPath+"\\", nfile);
}
file.SaveAs(path);
return RedirectToAction("List", "Product");
}
else
{
ModelState.AddModelError("", "Please Select an image");
return View();
}
}
else
{
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;
});

Resources