Upload multiple images in different folders using single button - c#

i am doing my project in mvc4 using c#
i my project i want to upload two image files from a folder so i use the following code.
View:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
Controller:
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
actually my need is that i want to upload these images in different folders on a single submit button. (That is file1 into Folder1 and file2 into Folder2) is that possible??

You have many solutions.
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
IList<HttpPostedFileBase> list = (IList<HttpPostedFileBase>)files;
for (int i = 0; i < files.Count(); i++)
{
if (list[i].ContentLength > 0 && i == 0)
{
var fileName = Path.GetFileName(list[i].FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
file.SaveAs(path);
}
else if (list[i].ContentLength > 0)
{
var fileName = Path.GetFileName(list[i].FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder2"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

Related

I want to insert multiple Image to the folder and path and also some data to database in ASP.net MVC

I want to insert multiple Image to the folder and path and also some data to database in ASP.net MVC.
Action
[HttpPost]
public ActionResult SaveProduct(ProductViewModel model, IEnumerable<HttpPostedFileBase> file)
{
try
{
Product pvm = new Product();
string upload = string.Empty;
foreach (var item in file)
{
string filename = Guid.NewGuid() + Path.GetExtension(item.FileName);
string filepath = "~/Images/" + filename;
item.SaveAs(Path.Combine(Server.MapPath("~/Images"), filename));
upload += filepath + ":";
}
string[] patharray = upload.Split(':');
pvm.product_name = model.product_name;
pvm.product_description = model.product_description;
pvm.is_new = model.is_new;
pvm.is_discount = null;
pvm.new_price = model.new_price;
pvm.old_price = model.old_price;
pvm.img1 = patharray[0].ToString();
pvm.img2 = patharray[1].ToString();
pvm.img3 = patharray[2].ToString();
pvm.img4 = patharray[3].ToString();
pvm.category = null;
pvm.quantity = model.quantity;
pvm.offer_title = null;
pvm.star = null;
pvm.CategoryID = model.CategoryID;
pvm.SubCategoryID = model.SubCategoryID;
db.Products.Add(pvm);
db.SaveChanges();
Console.WriteLine(pvm.ToString());
}
return RedirectToAction("AddProduct");
}
View
<form class="form-inline">
#using (Html.BeginForm("SaveProduct", "AdminSide", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-md-10"><input type="file" name="file" /></div>
<div class="col-md-10"><input type="file" name="file" /></div>
<div class="col-md-10"><input type="file" name="file" /></div>
<div class="col-md-10"><input type="file" name="file" /></div>
<input type="submit" value="Save" class="btn btn-block btn-primary" />
}
</form>

file control doesn't initialized in edit page - razor pages

I use asp.net core razor pages to create my application, in my create page, I have two file controls, one for upload icon image and the other for uploading detail images. But when I click edit button, all of the fields were initialized, except the two file controls. Please check my code. Anyone can help?
In my razor page:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Product.Icon" class="control-label"></label>
<input asp-for="#Model.Icon" type="file" />
<span asp-validation-for="Product.Icon" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label”>Detail Images(support multi-uploading):</label>
<input type="file" id="fUpload" name="files" multiple />
</div>
</div>
</div>
In my page model:
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Product = await _context.Products
.Include(p => p.Shop).SingleOrDefaultAsync(m => m.ID == id);
if (Product == null)
{
return NotFound();
}
ViewData["Shop"] = new SelectList(_context.Shops, "ID", "Name");
return Page();
}
public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
if (!ModelState.IsValid)
{
return Page();
}
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
if (!Directory.Exists(uploads))
{
Directory.CreateDirectory(uploads);
}
if (this.Icon != null)
{
var fileName = GetUniqueName(this.Icon.FileName);
var filePath = Path.Combine(uploads, fileName);
this.Icon.CopyTo(new FileStream(filePath, FileMode.Create));
this.Product.Icon = fileName;
}
if (files != null && files.Count > 0)
{
foreach (IFormFile item in files)
{
if (item.Length > 0)
{
var fn = GetUniqueName(item.FileName);
var fp = Path.Combine(uploads, fn);
item.CopyTo(new FileStream(fp, FileMode.Create));
this.Product.ProductImages = this.Product.ProductImages + fn + "^";
}
}
}
_context.Attach(Product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(Product.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
The most important part of your page is missing from the code you provided - the <form> tag. For file uploading to work, you must specify that the method is post and you must also provide an enctype attribute with its value set to multipart/form-data:
<form method="post" enctype="multipart/form-data">
...
Ref: https://www.learnrazorpages.com/razor-pages/forms/file-upload

Why is MVC HttpPostedFileBase always null?

This is my View
Test Upload File
<form action="#Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
This is my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = file.FileName;
var path = Path.Combine(Server.MapPath(#"\Upload"), fileName);
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
}
return View();
}
The problem is the HttpPostedFileBase files is always null. I cant find the problem.
Here is an example how to use form onsubmit method
Your HTML part
<form id="formTest" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
script
<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
e.preventDefault();
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('files');
if (fileInput != "" && fileInput.files.length > 0) {
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
var url = '#Url.Action("Index","Home")';
xhr.open('POST', url);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
}
}
return false;
}
}
</script>
C#
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return View();
}
}
You can also handle files with Request.Files like this:
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
}
And for your second question, please try to use it between Html.BeginForm instead of form like this:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<label>Filename:</label>
<input type="file" name="file1"/>
<input type="submit" name="submit" value="Upload" />
}

Single file uploads instead of multiple files in asp.net mvc

I'm trying to make a website using asp.net mvc 4 where I can store data in MSSQL db & store uploaded image files in local storage. So far data is storing successfully but whenever I select multiple images to upload, it only uploads the first selected image only. Here are my codes,
Controller
[HttpPost]
public ActionResult FlatManager(FlatMgt FlatTable, HttpPostedFileBase[] files)
{
if (Session["username"] != null)
{
if (ModelState.IsValid)
{
var AddFlat = FlatTable.Flats;
db.FlatInfoes.Add(AddFlat);
db.SaveChanges();
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
{
int imageCount = 0;
string picName = FlatTable.Flats.flatno.ToString() + "-" + imageCount;
string picExt = Path.GetExtension(file.FileName);
if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg")
{
picExt = ".png";
}
string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
file.SaveAs(path);
imageCount++;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
else
{
TempData["add_fail"] = "Error! Wrong File Type(s)! Please Try Again.";
return RedirectToAction("FlatManager");
}
}
TempData["add_success"] = "Information Added Successfully!";
return RedirectToAction("FlatManager");
}
else
{
TempData["add_fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlatManager");
}
}
else
{
return RedirectToAction("Login");
}
}
View
#using (Html.BeginForm("FlatManager", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<label for="file">Upload Image:</label>
<input type="file" multiple="multiple" name="files" id="file" style="width: 100%;" /><br />
<input type="submit" value="Add" />
}
I can't find any error in my codes. How can I solve this problem? Will be really helpful if someone helps. Thanks.

Kendo File uploader not getting Controller method called

I have file upload html code as:
#using (Ajax.BeginForm("UploadImage", "PP", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="files">
<button class="buttoncss">Upload</button>
//<input type="submit" name="Submit to server">
(also tried with input type="submit"
}
In PPController i have method as below:
[HttpPost]
[ValidateAntiForgeryToken]
public void UploadImage(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
But my controller method is not getting called.
What can be the problem?
Please help me.

Categories