ASP.NET MVC4 multiple file upload not work from mobile - c#

I have the following code, you can enter the site from url: http://nirh1989-001-site1.itempurl.com/
When i open the url from desktop, i can upload multiple files at once, but when i open the url from my mobile browser i can only upload 1 file at a time.
Why?
Index.cshtml:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="container">
<div class="form-horizontal">
<div class="form-group">
<p></p>
<label for="file">Upload Photo:</label>
<input type="file" name="file" id="file" accept="image/*" multiple="multiple" required />
</div>
<div class="form-group">
<div>
<input type="submit" value="Upload" class="btn btn-default" />
</div>
</div>
</div>
</div>
<hr />
<div class="gallery">
#if (ViewBag.Images != null)
{
var imgID = 0;
foreach (var image in (IEnumerable<string>)ViewBag.Images)
{
imgID++;
<a class="fancybox" rel="group" href="#Url.Content(image)">
<img id="#imgID" src="#Url.Content(image)" style="height: 100px; width: 100px;" />
</a>
}
}
</div>
}
Controller:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("/Content/Photos")).Select(f => "/Content/Photos/" + Path.GetFileName(f));
return View();
}
//POST: Home
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> file)
{
if (file != null)
{
foreach (var item in file)
{
string fileName = Path.GetFileName(item.FileName);
string imgPath = Server.MapPath("~/Content/Photos/");
item.SaveAs(imgPath + fileName);
}
}
ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("/Content/Photos")).Select(f => "/Content/Photos/" + Path.GetFileName(f));
return View();
}
}

Apparently there was nothing wrong with my code... the problem was the mobile, i tried to upload multiple files from a folder in the phone that for some reason not allowed multiple choices... tried to upload from gallery and everything is ok

Related

How to upload file to asp .net?

I am looking for a solution on how to send a file using a form to an asp application. I am writing in the asp .net framework MVC Razor.
My form:
<div class="container">
<div class="col-md-2">
#using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"}))
{
<div class="form login-form">
<label for="username" class="text-info">Wczytaj plik:</label>
<input type="file" name="file" id="file" />
</div>
<div id="register-link" class="text-right">
<input type="submit" class="btn btn-success" value="Importuj" />
</div>
#ViewBag.Message
}
</div>
</div>
My controller:
[HttpPost]
public ViewResult Data(HttpPostedFile file = null)
{
if(file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Upload/Data"), Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Succes";
}
return View("AdminDataView", students);
}
Unfortunately, the above code does not work, am I doing something wrong with it, is there another option to upload the file to asp?
I think there is a typo and i suggest you that use ActionResult instead of ViewResult.
Defference between ActionResult & ViewResult
the typo is: new { enctype="multipart/form-data"}) not new { encrypte = "multipart/form-data"})
Sample Code:
View
#using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new {
enctype="multipart/form-data"}))
{
<div>
#Html.TextBox("file", "", new { type= "file"}) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
}
Controller
[HttpPost]
publicActionResultUploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
Please refer below link this gives you better understanding.
https://stackoverflow.com/a/60519052/7761461
Hope this will surely help you.

Redirect not including application name, and authentication not working properly

I'm attempting to implement an "Admin" login so my users can add content on their own and I don't need to worry about a stranger somehow routing to a Create/Edit/Delete Action. Im putting the Username and password to authenticate against in the Web.config file and everything works fine in Visual Studio. But when I publish the application to IIS the authentication seems to fail and when redirecting back to the Login action I'm getting a 404 Not Found Error. When redirecting or returning the View the route isn't including the Application name {application name}/Authentication/Login instead its just returning Authentication/Login but when I attempt to visit one of the Create actions it will successfully redirect, this is driving me insane and any help is much appreciated.
RouteConfig.cs
routes.MapRoute(
name: "Authentication",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Authentication", action = "Login", id = UrlParameter.Optional }
);
AuthenticationController.cs
namespace ShipleySwine.Controllers
{
public class AuthenticationController : Controller
{
// GET: Authentication
public ActionResult Login()
{
ViewBag.Message = TempData["Message"];
return View();
}
[HttpPost]
public ActionResult Login(AuthenticationViewModel vm)
{
//if (ModelState.IsValid)
//{
// if (vm.user.userName == System.Configuration.ConfigurationManager.AppSettings["Admin"].ToString() && vm.user.password == System.Configuration.ConfigurationManager.AppSettings["adminPass"].ToString())
// {
// Session["Authentication"] = "Success";
// return RedirectToAction("Index", "Admin");
// }
// else
// {
// TempData["Message"] = "Login failed, Incorrect username/password";
// return Redirect("/ShipleySwine/Authentication/Login");
// //return RedirectToAction("Login", "Authentication");
// }
//}
//else
//{
// //return RedirectToAction("Login", "Authentication");
// return Redirect("/ShipleySwine/Authentication/Login");
//}
if (ModelState.IsValid)
{
if (vm.user.userName == System.Configuration.ConfigurationManager.AppSettings["Admin"].ToString() && vm.user.password == System.Configuration.ConfigurationManager.AppSettings["adminPass"].ToString())
{
Session["Authentication"] = "Success";
return RedirectToAction("Index", "Admin");
}
else
{
TempData["Message"] = "Login failed, Incorrect username/password";
ViewBag.Message = "Login failed, Incorrect username/password";
return View();
}
}
else
{
return View();
}
}
}
}
Login.cshtml
#model ShipleySwine.ViewModels.AuthenticationViewModel
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="col-4">
</div>
<div style="padding: 50px; margin-top: 25px;" class="col-4 backgroundcolor rounded">
<h2 class="text-center">Login</h2>
<form action="/Authentication/Login" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input name="user.userName" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="user.password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
#if (ViewBag.Message != null)
{
<p class="text-danger font-weight-bold">#ViewBag.Message</p>
}
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div class="col-4">
</div>
</div>
Web.config
<appSettings>
<add key="Admin" value="{username}"/>
<add key ="adminPass" value="{password}"/>
</appSettings>
Create Action w/ successful Redirect
public ActionResult Create()
{
if(Session["Authentication"] != null)
{
if(Session["Authentication"].ToString() != "Success")
{
return RedirectToAction("Login", "Authentication");
}
else
{
ViewBag.BoarId = db.Boars.Max(boarid => boarid.Boar_Id) + 1;
return View();
}
}
else
{
return RedirectToAction("Login", "Authentication");
}
}
Apparently I didn't give myself enough time...
Figured it out after looking at it closely. I hardcoded the action in the Login.cshtml
<form action="/Authentication/Login" method="post">
This works just fine in Visual Studio running on Localhost but when published to IIS the route doesn't exist. In reality it wasn't redirecting because the form wasn't successfully passed to the controller
Correct Login.cshtml
<div class="row">
<div class="col-4">
</div>
<div style="padding: 50px; margin-top: 25px;" class="col-4 backgroundcolor rounded">
<h2 class="text-center">Login</h2>
#using (#Html.BeginForm("Login", "Authentication", FormMethod.Post))
{
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input name="user.userName" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="user.password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
if (ViewBag.Message != null)
{
<p class="text-danger font-weight-bold">#ViewBag.Message</p>
}
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
}
</div>
with the important change being the tag helper #using (#Html.BeginForm("Login", "Authentication", FormMethod.Post))
Just change your form to this :
<form action="#Url.Action("Login")" method="post">

MVC cant upload file

Im fairly new to .NET Core MVC and trying to create a simple application where a user can upload a file and it saves to a home folder, currently i've followed a tutorial which at least seems to be a step in the right direction. however my post method isn't being hit when I click the submit button. does anybody have any insights as to why this is?
Here is my controller code:
namespace GraduateOutcomesConverter.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpPost("UploadFiles")]
public async Task<IActionResult> FileUpload(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
var filePaths = new List<string>();
foreach (var formFile in files)
{
if(formFile.Length > 0)
{
var filePath = Path.GetTempFileName();
filePaths.Add(filePath);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
return Ok(new { count = files.Count, size, filePaths });
}
And my View
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Please Upload An Excel File.</p>
<input type="file" name="datafile" style="margin-left: 10px; margin-top:
15px; vertical-align: top; font-size:18px; background-color: white; margin-
left:160px; margin-top:15px; width:250px; height:40px /">
</div>
<form method="post" enctype="multipart/form-data" asp-
controller="UploadFiles" asp-action="FileUpload">
<div class="form-group">
<div class="col-md-10">
<p>Please Upload An Excel File.</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form>
Any help would be much appreciated
Thanks
The given controller name to form element is Invalid. You probably need to change it to Home
Your current code
<form method="post" enctype="multipart/form-data" asp-
controller="UploadFiles" asp-action="FileUpload">
It should be;
<form method="post" enctype="multipart/form-data" asp-
controller="Home" asp-action="FileUpload">

HttpPostedFileBase null

HttpPostedFileBase always provides null, I looked online various solutions but the result does not change, I am attaching the code, can you help me?
being that I already have a model in my view I asked myself if it is possible to do this, I do not have to upload more than one file.
ps: I also tried to change the style of the input but it is not changed
I apologize if the English is bad but I have translated with the translator of google
#model WebElementware.Models.TAB_LAVORA_CON_NOI
#{
ViewBag.Title = "WorkWithUs";
}
<form action="#Url.Action("WorkWithUs","Home")" method="post" enctype="multipart/form-data">
#using (Html.BeginForm("WorkWithUs", "Home", FormMethod.Post, new { TBLCN = Model, enctype = "multipart/form-data"}))
{
<label for="file">Inviaci il tuo curriculum:</label>
<input type="file" name="file" id="file" />
}
</form>
<section>
<center>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Cerca!" class="btn btn-default" />
</div>
</div>
</center>
</section>
controller
[HttpPost]
public ActionResult WorkWithUs(TAB_LAVORA_CON_NOI TBLCN ,HttpPostedFileBase file)
{
string Message = "";
if (ModelState.IsValid)
{
TBLCN.LETTO = false;
using (DB_WEB_ELEMENTWAREEntities1 DB = new DB_WEB_ELEMENTWAREEntities1())
{
DB.TAB_LAVORA_CON_NOI.Add(TBLCN);
DB.SaveChanges();
}
}
else
{
Message = "Invalid Request";
}
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
ViewBag.Message = Message;
return View(TBLCN);
}

Entity Framework "Edit" ActionResult which keeps or uploads new html file input originaly posted and saved through the "Create" ActionResult

I have a MVC 5 controller with views, using Entity Framework project.
I have a controller and view for my Item Model:
public partial class Item
{
public int ItemID { get; set; }
public string ImageURL { get; set; }
}
I changed the Entity Framework Create view and controller to post an html file input and save the file path as the ImageURL
A snippet from the view looks like this:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
The controller's Create ActionResult looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ItemID,ImageURL")] Item item, HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
file.SaveAs(path);
item.ImageURL = "/Uploads/" + file.FileName;
db.Items.Add(item);
db.SaveChanges();
}
ViewBag.Message = "Upload successful";
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = "Upload failed";
ViewBag.ItemTypeID = new SelectList(db.ItemTypes, "ItemTypeID", "ItemType1", item.ItemTypeID);
return View(item);
}
}
As you can see I use var fileName = Path.GetFileName(file.FileName); and item.ImageURL = "/Uploads/" + file.FileName; To populate my ImageUrl. The file itself is saved on the server.
Now my issue is that I don't know how to get the "Edit" view and ActionResult to allow me either to keep the same image or upload a new image.
How can I do this?
What I have done so far is in the Edit view to write:
<div class="form-group">
#if (Model.ImageURL == null)
{
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
else
{
/*Keep or upload new image here*/
}
</div>
What would I need to write in that else {...} and what would I need to write in the controller's public ActionResult Edit(int? id) {...} ?
Just show Image in the img control and below that use another file control , in case user need to change the uploaded image..
<div class="form-group">
#if (Model.ImageURL == null)
{
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
else
{
/*show Image in an img control using image path*/
<img src="#Model.ImageURL" height="100" width="100" />
<fieldset>
<legend>change the file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
and at Action part everything will be same , remove the old file and save new one and update db as well.
also Don't forget to use form as you have used in the create view.
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
if image is not uploaded For the particular item How you will edit . You can do create and edit both in single action method by
var itemInDb = db.items
.Where(c => c.itemid== id) // or whatever your key is
.SingleOrDefault();
if (itemInDb != null)
db.Countries.ApplyCurrentValues(item);
else
db.Countries.AddObject(item);
db.SaveChanges();
if multiple images are there for single image you can loop it

Categories

Resources