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">
Related
Below is the form code
#{
ViewData["Title"] = "ModelTrain";
ViewBag.Center = true;
}
<form method="post" class="text-center" asp-controller="Home" asp-action="Index">
<div class="form-group text-center w-50 mx-auto">
<input type="text" name="url" class="form-control my-2" id="url" placeholder="Добавить ссылку профиля " />
</div>
<input type="submit" value="Обучмть модель" class="submit btn btn-secondary" />
</form>
And Below is the Controller code
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(String url)
{
ControlObject control = new ControlObject();
control.body_profile = url;
control.profile = true;
var json = JsonConvert.SerializeObject(control);
var firebaseClient = new FirebaseStorage("hackathontest-e8d57.appspot.com");
var path = #"C:\Users\emiol\source\repos\HackathonFiles\HackathonFiles\TextFile1.txt.txt";
System.IO.File.WriteAllText(path, json);
using (FileStream fs = System.IO.File.Open(path, FileMode.Open))
{
var result = await firebaseClient.Child("TextFileForUrls.txt").PutAsync(fs);
}
return RedirectToAction("Index","Image");
}
}
}
`
It returns a 404 error when i try to post back to the form. This doesn't happen when testing locally. can someone point me to a possible solution please as I've been stuck for a long time on this
Try removing div class and have your form code like below:
#{
ViewData["Title"] = "ModelTrain";
ViewBag.Center = true;
}
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text" name="url" class="form-control my-2" id="url" placeholder="Добавить ссылку профиля " />
<input type="submit" value="Обучмть модель" class="submit btn btn-secondary" />
</form>
Most probably, your form code is incorrectly written and some classes are incorrectly interpreted. Try the below basic approach first and then add your custom changes one by one and see where it fails (if the above does not work).
Check out this tutorial for reference: https://www.aspsnippets.com/Articles/ASPNet-Core-Form-Submit-Post-Example.aspx
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.
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);
}
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
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