Getting path directory from input file ASP.Net - c#

I read up on how to get a file input to select a directory, link here how to get folder directory from html input type file or any other way
Now the issue I have is to get the list of files it picks up from the directory:
folder count
OR
Get the directory path in the backend of the ASP.Net when the user clicks on the submit button.
The code:
// POST: /Gallery/CreateImage
[HttpPost]
public ActionResult CreateImage(FormCollection collection, HttpPostedFileBase file)
{
try
{
//For each file in folder do the following
string title = collection["title"];
string description = collection["description"];
bool isSlide = collection["isSlider"] == "on" ? true : false;
bool isGallery = collection["isGallery"] == "on" ? true : false;
gallery = new Gallary(title, description, Path.GetExtension(file.FileName).Replace(".",string.Empty), isSlide, isGallery, Category.Drawing);
gallery.AddToGallery(gallery, file);
return View("GalleryManage", "Gallery");
}
catch
{
return View("GalleryManage", "Gallery");
}
}
HTML Code:
<div class="form-horizontal">
#using (Html.BeginForm("CreateFolder", "Gallery", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="box-body">
<div class="form-group">
<p>Please make sure that your folder structure is in the following format:</p>
<ol>
<li>Root Folder</li>
<li>-Art Category Folder</li>
<li>--Project Folder</li>
<li>---Images</li>
</ol>
</div>
<div class="form-group">
<label for="file">Please choose root folder</label>
<input type="file" name="folderUpload" webkitdirectory directory multiple />
</div>
<br />
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
}
</div>

As user3559349 points out in the comments.
I changed the CreateImage method post to ActionResult CreateImage(IEnumerable<HttpPostedFileBase> folderUpload).
I was able to get all the images uploaded.

Related

File upload using ASP.NET and HTML form

I am trying to create the functionality that allows to upload the image and store it into the db.
I have this input field in my HTML form:
#using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post))
{
<div class="modal" id="NewTRModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-xl" style="width:1250px;">
<div class="modal-content">
<div class="box5">
<div>
<label for="file-upload" class="custom-file-upload">
Upload Image1
</label>
<input id="file-upload" type="file" name="image1"/>
</div>
<div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4"> Submit</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">Hide</button>
</div>
</div>
</div>
</div>
}
And I am trying to get the file in my controller through
IFormFile file = Request.Form.Files["image1"];
However, for some reasons after I am clicking submit button the Request.Form.Files is empty.
I will appreciate any advice.
Web browsers will upload files properly only when the HTML form
element defines an enctype value of multipart/form-data:
#using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input id="file-upload" type="file" name="image1"/>
...
}
Without the enctype attribute, the browser will transmit only the name of the file and not its content.
Then in the controller action method you can use the same name as defined in the <input> tag as a parameter:
[HttpPost]
public ActionResult AddTR(HttpPostedFileBase image1)
{
if (image1 != null && image1.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath(#"~/"), Path.GetFileName(image1.FileName));
image1.SaveAs(path);
}
...
}
In case you are using ASP.NET Core (what you didn't mention in the question) you can define the enctype attribute and than use:
[HttpPost]
public IActionResult AddTR()
{
IFormFile file = Request.Form.Files["image1"];
....
}

File upload ASP.NET MVC in multiple submits form

I have a small tool that downloads reports based on the specified options. The download works well. And now, I want to also upload a file to the folder and then further use it.
The problem is that I already have one submit button on the form that is used for the download and when I am adding another button for the upload, only download is triggered.
I tried to resolve it using an #Html.ActionLink(), but no success. Is there any proper way to resolve the issue? I know that there is a possibility to capture the submit value and then check in one main ActionResult in the Controller and redirect to the respective ActionResult, but I don't want to do it, since there are too many POST Actions in one controller.
Here is my View - download.cshtml:
#using (Html.BeginForm())
{
<fieldset>
<div class="title">Click to download report</div>
<div class="field">
<input id="downloadBtn" type="submit" class="button" value="Download" />
</div>
</fieldset>
<fieldset id="Option_ClientInfo">
<div class="title">
Image
</div>
<div class="field">
<input type="file" name="ImageUpload" accept="image/jpeg" />
<p>#Html.ActionLink("Upload", "UploadImage", new { controller = "Home", enctype = "multipart/form-data"}, new { #class = "button" })</p>
</div>
</fieldset>
}
And the controller - HomeController.cs:
public partial class HomeController : Controller
{
// some functions
// ....
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase imageFile)
{
string path = Path.Combine(this.GetImageFolder, Path.GetFileName(imageFile.FileName));
imageFile.SaveAs(path);
return null;
}
// additional POST functions for other forms
// ....
[HttpPost]
public ActionResult Download(Info downloadInfo)
{
// perform checks and calculations
return new reportDownloadPDF(downloadInfo);
}
}
Any suggestion in appreciated.
The solution is just separate upload and download functionalities using two forms so it wont conflict while submitting.
#using (Html.BeginForm())
{
<fieldset>
<div class="title">Click to download report</div>
<div class="field">
<input id="downloadBtn" type="submit" class="button" value="Download" />
</div>
</fieldset>
<fieldset id="Option_ClientInfo">
<div class="title">
Image
</div>
</fieldset>
}
#using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<div class="field">
<input type="file" name="ImageUpload" accept="image/jpeg" />
<p>
<input id="uploadBtn" type="submit" class="button" value="Upload" />
</p>
</div>
</fieldset>
}
There is another issue as well. Image control name and Post Action method parameter name should be same.
So your upload image Post Action method will be:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase imageUpload)
{
string path = Path.Combine(this.GetBasePath + "/img/tmp/", Path.GetFileName(imageFile.FileName));
imageFile.SaveAs(path);
return null;
}

Upload multiple files with single input Asp Mvc

I want to upload multiple files including Word Documents, Pdf and Images.
I need to use a single input for files because we don't know how many files will be uploaded.
My code is this but I have problem that I can't send files to server side.
Controller Code :
public ActionResult Create([Bind(Include = "Id,Content")] Message message, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
// Object save logic
SaveFiles(message,files);
return RedirectToAction("Index");
}
return View(message);
}
Part of view code :
<form name="registration" action="">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label for="Content" >Content:</label>
<textarea class="form-control compose_content" rows="5" id="Content" name="content"></textarea>
<div class="fileupload">
Attachment :
<input id="files" name="files" type="file" multiple />
</div>
</div>
<button type="submit" class="btn btn-default compose_btn" >Send Message</button>
</form>
I don't have problem with saving files and saving the object.
only problem :
files list is null.
I order to upload files, your form needs to include the enctype= multipart/form-data attribute.
<form name="registration" action="" enctype= "multipart/form-data">
or better
#using (Html.BeginForm(actionName, controllerName, FormMethod.Post, new { enctype= "multipart/form-data" }))
and I strongly recommend you pass a model to the view and use the strongly typed HtmlHelper methods to create your html for the properties of your model.

MVC5 Razor Upload Image

I'm trying to create a page that whilst editing an "Asset" the user can upload a picture within a partial view.
On submitting the picture I would like the filename to be saved to server location and prefixed with its Asset ID number for obvious reasons and then return the partial view but with the picture in.
So when the user submits the edit page the changed details as well as a new shiny picture url is saved to the DB.
Heres what I have so far.
Edit View (Edit.cshtml)
#model Asset_Manager.DB.Asset
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Asset</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Aid)
**** other fields
<div class="form-group">
#Html.LabelFor(model => model.Picture_Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Partial("~/Views/Asset/UploadAssetImage.cshtml",Model)
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Partial Upload View (UploadAssetImage.cshtml)
#model Asset_Manager.DB.Asset
#using (Html.BeginForm("UploadPicture", "Asset", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img src="#Model.Picture_Location" alt="#Model.Description" width="250" height="250" /><br />
<input type="file" name="file" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
<input type="hidden" name="id" value="#Model.Aid" />
}
and finally Controller Method (AssetController.cs)
[HttpPost]
public ActionResult UploadPicture(int id,FormCollection collection)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = "Asset_" + id + "_" + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/AssetImages/"), fileName);
file.SaveAs(path);
}
}
Asset A = new Asset();
A = _dal.GetAssetByID(id);
return PartialView("UploadAssetImage", A.Aid);
}
Now My Issues
Each time I try to submit a photo I get kicked right out to the Asset index (Index.cshtml) page let alone be able to see if sending the entire edit works.
Also the breakpoint under the controller method doesn't trigger so I cant trace where the issue could be.
Any Help / Examples / Pointers in the right direction would be appreciated.
You have a form within a form, which is invalid HTML. The outermost form is what is being submitted, and this form, importantly, does not include the enctype="multipart/form-data" attribute. Add that attribute to your form in the view and remove the form in your partial.

How to upload file in ASP.NET razor

I want to upload a file in folder image.
I use ASP.NET with MVC4 and razor.
I have this in my View :
<div class="editor-label">
#Html.Label("Descriptif")
</div>
<div class="editor-field">
<input type="file" name="fDescriptif" />
#Html.ValidationMessageFor(model => model.fDescriptif)
</div>
[...]
<p>
<input type="submit" value="Create" />
</p>
In my controller :
[HttpPost]
public ActionResult Create(formation formation)
{
if (ModelState.IsValid)
{
db.formations.Add(formation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(formation);
}
In my model :
public string fDescriptif { get; set; }
I have no idea what I must do to upload my file in my folder "image" and save just the name of my file in my database. When I validate my form it's my complete path who saved.
On your view make sure you have added enctype = "multipart/form-data" to your form tag, and then try like this:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" }))
And you can Get your file in Controller Action AS:
[HttpPost]
public ActionResult Create(formation formation,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
// Get your File from file
}
return View(formation);
}
you can find many questions like this, even on SO many answers have been given for this topic.
Here are 2 of the links. you should find your answer in this links. and many more other answers are there for this on SO. just google it, and you will find them.
https://stackoverflow.com/a/5193851/1629650
https://stackoverflow.com/a/15680783/1629650
Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):
#using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
#Html.TextBoxFor(m => m.File, new { #type = "file" })
AND IN CONTROLLER
[HttpPost]
public ActionResult ACTION(ViewModels.Model taskModel)
{
string path = #"D:\Projects\TestApps\uploadedDocs\";
if (taskModel.File != null) {
taskModel.File.SaveAs(path +taskModel.TaskTitle
+ taskModel.File.FileName);
newUserProject.DocumentTitle = taskModel.TaskTitle
+ taskModel.File.FileName;
newUserProject.DocumentPath = path + taskModel.File.FileName;
}
}
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
And your controller should be as below
[HttpPost]
public ActionResult Index(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 RedirectToAction("Index");
}

Categories