File upload using ASP.NET and HTML form - c#

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"];
....
}

Related

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.

Popup to Upload files MVC

I need to upload some xml files .For this I need to open from my MVC application a popup to load a file .I wrote the code below.In the controller I see the loaded file .
Upload.cshtml:
#using (#Html.BeginForm("UploadFile", "UploadFileController", FormMethod.Post, new { #id = "uploadForm", #enctype = "multipart/form-data" }))
{
<div>
#Html.TextBoxFor(m => m.FileName, new { type = "file" })
<button type="submit" class="btn">Upload</button>
</div>
}
Controller :
[HttpPost]
public ActionResult UploadFile(UploadFileModel uploadFileModel)
{
....
}
Model:
public class UploadFileModel
{
public int Id { set; get; }
public HttpPostedFileBase FileName { get; set; }
}
Now ,the "Upload.cshtml" is a part and appear in the home page .
1.How can I transform it in a separate form ?This part appear when I press a button.
2.How can I show in the search dialog just xml files ?
Thanks .
As it was mentioned before , it's front-end problem and nothing to do with c# and controller. So please Modify Upload.cshtml :
<button type="button" class="btn btn-default" id="showPopup">show popup</button>
<form id="uploadForm" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#Html.TextBoxFor(m => m.FileName, new { type = "file" })
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">close form</button>
<button type="submit" class="btn btn-success" id="">Upload</button>
</div>
</div>
</div>
Now with jquery :
$('#showPopup).click(function(){
$('#uploadForm').modal();
});
another option is Bootbox.js.
hope it helps.

How I can use html tags with bootstrap in asp.net mvc for get a result from controller?

Hey Guys I have a problem with my ASP.NET MVC Application. I want to make a Search textfield and a image button in my application. If I input a valu in the textfield I want use this value for search in a list and send the result to the View. I use bootstrap because it looks fine.
here is my code: Index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("Search", "HomeController"))
{
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" id="txtSearch" class=" search-query form-control" placeholder="Search" name="txtSearch" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
}
Here is my Controller:
[HttpPost]
public ActionResult Search(string txt)
{
List<string> petList = new List<string>();
petList.Add(txt);
ViewBag.liste = petList;
return View();
}
Your input does not have a name attribute that matches the parameter in the method so it is not bound. Change it to
<input type="text" id="txtSearch" class="..." name="txt" />
or change the method to match the current name attribute
[HttpPost]
public ActionResult Search(string txtSearch)
Side note: Assuming your controller is named HomeController then it should be #using (Html.BeginForm("Search", "Home")), not #using (Html.BeginForm("Search", "HomeController")) (which would only work if you have a controller named HomeControllerController)

Get files for each language in model (MVC 3) using HttpContext to save them in separate table

I have this simple piece of HTML code:
<div>
<input type="file" name="english-file" />
</div>
<div>
<input type="file" name="french-file" />
</div>
I used in my model, the following C# line code:
object receivedFiles = HttpContext.Current.Request.Params["english-file"];
but that object returns null always.
Of course that I can use HttpContext.Current.Request.Files but I want to sepparate files by languages (the above HTML code is simple but someone could add more files to english than french with +Add files button) and save them in sepparate table.
How could I do that?
That's not how files are uploaded. You should look in Request.Files["english-file"] after setting the proper enctype on the form.
Let's take an example:
#using (Html.BeginForm("upload", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="english" />
</div>
<div>
<input type="file" name="french" />
</div>
<button type="submit">Upload</button>
}
and in the controller action:
[HttpPost]
public ActionResult Upload()
{
var englishFile = Request.Files["english"];
var frenchFile = Request.Files["french"];
...
}
or even better:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase english, HttpPostedFileBase french)
{
...
}
or even better:
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
...
}
assuming you adjust the names of the file inputs:
#using (Html.BeginForm("upload", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="files" />
</div>
<div>
<input type="file" name="files" />
</div>
<button type="submit">Upload</button>
}
I also invite you to read the following blog post.

Categories