I have a requirement of uploading the multiple documents with the help of file upload control. The same thing I had done for the Image type. It is working perfectly since it takes only 1 image file. But the multiple file upload is not working. What's the flaw in my code How can I do it?
Html Code:
----------
#using (Html.BeginForm("Index", "Block", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-lg-4" id="FileUp">
<label>Upload File</label>
#Html.TextBoxFor(m=>m.DocumentFilesPath, new { #name="fileUpload", #id="fileUpload", #type = "file", #multiple="multiple", #class="form-control dropDownLabel", #onchange="fileTypeCheck()" } )
</div>
// What should I specify the type for DocumentFilesPath in #Html.TextBoxFor(m=>m.DocumentFilesPath) in my strongly typed model?
<div class="col-lg-8>
<button type="button" class="btn btn-primary" id="SaveBlock" onclick="checkSubmit()">
<span class="glyphicon glyphicon-floppy-save"></span>Save
</button>
</div>
}
My Controller Action:
---------------------
[Authorize]
[HttpPost]
public ActionResult Index(BlockViewModel model)
{
if (model.BlockID == 0)
{
HttpPostedFileBase file = Request.Files["imgUpload"] as HttpPostedFileBase; // I am able to get the single file here
if (file.ContentLength > 0)
{
file.SaveAs(Server.MapPath("~/Images/uploads/") + file.FileName);
model.ImageFilepath = Server.MapPath("~/Images/uploads/") + file.FileName;
}
IEnumerable<HttpPostedFileBase> docFiles = Request.Files["fileUpload"] as IEnumerable<HttpPostedFileBase>; // But here docFiles is null
//IEnumerable<HttpPostedFileBase> docFiles = fileUpload as IEnumerable<HttpPostedFileBase>;
if (docFiles != null)
{
foreach (HttpPostedFileBase docFile in docFiles)
{
if (docFile.ContentLength > 0)
{
docFile.SaveAs(Server.MapPath("~/Images/Files/") + docFile.FileName);
model.DocumentFilesPath = Server.MapPath("~/Images/Files/") + docFile.FileName;
}
}
}
}
Refer this link for multiple file uploads ,,
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/
Basic Idea is We can simply have
multiple file inputs all with the same name.
<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>
and in 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"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
Related
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
I am trying to upload a single .csv file in ASP.NET MVC. In my .ascx file, I have:
<div>
<input type="file" name="file" id="file" />
   
<input type="submit" name="btnSubmit" id="btnSubmit" value="Upload" />
</div>
The controller action is:
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return View();
}
The problem is that I always get file as Null in the Upload Action. Any suggestions on how to get this working?
Are you sure you have a
<form enctype="multipart/form-data" method="post">
<div> bla bla
</div>
</form>
?
Edit :
method="post"
+
[HttpPost]
on your action