HttpPostedFileBase always returns null - c#

I am using MVC 4 and I tried for upload file concept.
Here is my code:
<div class="complianceSubDiv">
<div class="complianceLeftDiv">
#Html.Label("Upload the file")
</div>
<div class="complianceRightDiv">
<input type="file" id="file" name="file" />
</div>
</div>
My controller code like
[HttpPost]
public ActionResult ManageDocument(DocumentModel documentModel, HttpPostedFileBase file)
{
//some code
}
But the HttpPostedFileBase file always returns null. I have searched more answers in StackOverflow and other websites and I got the working answer is parameter of HttpPostedFileBase variable name and fileupload control name are same . So I put the same name on all sides, but it returns null only.
Anyone help to me?

Finally i got it
Now i replaced for #using (Html.BeginForm())
to
#using (Html.BeginForm("ManageDocument", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
It's working !

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase myFile)
{
myFile = Request.Files["file"];
if (myFile != null && myFile.ContentLength > 0)
{
// your code ....
}
return View();
}
You can use "Request.Files" to get the selected file, above is the code.

Related

ASP .NET MVC uploaded file is always null

I'm trying to upload a JSON file, but the MVC controller is always interpreting it as null.
View:
<h3>OR</h3><br>
#Html.TextBox("jsonFile", null, new { type = "file" })
<div class="col-md-offset-2 col-md-10 ">
<input type="submit" value="Create" class="btn btn-default submit-button" formaction="Create" />
</div>
Controller:
public ActionResult Create(HttpPostedFileBase jsonFile)
{
MessageBox.Show("Create");
String str;
if (ModelState.IsValid)
{
if (jsonFile != null)
{
MessageBox.Show("File Upload Success");
StreamReader jsonReader = new StreamReader(jsonFile.InputStream);
str = jsonReader.ReadLine();
MessageBox.Show(str);
}
else
{
MessageBox.Show("Null");
}
return RedirectToAction("Index");
}
return View(projectDetail);
}
Its the part of bigger program and I have used following code for form:
#using (Html.BeginForm( new { htmlAttributes = new { enctype = "multipart/form-data" } } ))
{
}
I get this button to upload files and file upload is also working well as I can see its uploaded status before I click Submit. Not sure why it's always null in the controller.
Have you decorated your action method with "HTTPPOST" attribute? I can't see that in your create action.
public ActionResult Create(HttpPostedFileBase jsonFile)
And also you have to update your form as blow to have controller and action method.
#using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new { id = "FormCreate", enctype = "multipart/form-data"}))

Upload file with input type file in form and c# HttpPostedFile

I try to user an input type file to upload a file but my code don't work.
the variable "filePosted" stay to null value.
My code :
HTML :
<form method="post" name="gestionmembre" runat="server" enctype="multipart/form-data">
#using (Html.BeginForm()){
<label class="lmembre" for="nom">Nom:</label>#Html.TextBox("nom")<br />
<label class="lmembre" for="prenom">Prénom:</label>#Html.TextBox("prenom", Request["Prenom"])<br />
<label class="lmembre" for="mail">Mail:</label>#Html.TextBox("mail", Request["mail"])<br />
<label class="lmembre" for="photo">Photo:</label><input id="phototelecharge" type="file" name="photo" value="Télécharger photo"/> <br />
<div class="errorform">#Html.ValidationSummary()</div>
<input id="ajoutmembre" type="submit" name="boutonmembre" value="Ajouter"/>
}
</form>
I don't know if I have to put this atributes in form tag (method runat enctype).
now, in the controler, in block to receive form values, I put :
else if (Request["boutonmembre"] == "Ajouter")
{
//Traitement de l'upload de l'image
HttpPostedFile filePosted;
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
}
The problem is in :
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
The variable fileposted is null.
In the webpage, I select a file fro a disk and the path of the file is realy indicate in the textbox.
Tks for help me.
David
Here is a simple example
Controller
namespace stackoverflow.Controllers
{
public class HomeController : Controller
{
public ActionResult PostFile(HttpPostedFileBase myFile)
{
System.Diagnostics.Debugger.Break();
return View();
}
}
}
View
#using (Html.BeginForm("PostFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="postdata">
<input type="file" name="myfile" id="myFile" />
<input type="submit" value="submit" />
</div>
}

How to POST a file to asp.net mvc app? [duplicate]

This question already has answers here:
File Upload ASP.NET MVC 3.0
(23 answers)
Closed 9 years ago.
I'm posting a simple text file to an asp.net MVC app. When I post using the form below, the form parameter is not null. But file is. Any ideas what I'm doing wrong?
<form method=post action="http://localhost/Home/ProcessIt"
enctype="application/x-www-form-urlencoded">
<input type=file id="thefile" name="thefile" />
<input type="submit" name="Submit" />
</form>
In the asp.net mvc app:
[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
HttpPostedFileBase file = Request.Files["thefile"];
...
}
This works for me:
View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// then save on the server...
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
Need to change the enctype to multipart/form-data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

Uploaded file is null

In ASP.NET MVC4, a file-upload view is always sending null to the controller.
I have no idea why, I don't know how to fix it and searching has proven unfruitful...
Controller method:
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase file)
{}
View:
#using (Html.BeginForm("uploadCustomImage", "W", new { id=ViewBag.id }, FormMethod.Post, new { enctype = "multipart/form-data", name="uploadingimage" }))
{
<input name="file" id="file" type="file" />
#Html.SubmitButton()
}
It enters into the controller fine, so routing is all good. But file is always null. I've tried several different things: renaming the input/object, not using a file argument and calling this:
HttpPostedFileBase file = Request.Files["file"];
(which also turns out null)
I tried including a formcollection as a parameter (with and without unnecessary form elements). Still this file is null.
I am of course selecting a file before I press submit =P I've tried multiple files; with very basic filenames (no weird unicode, even no spaces) and also weirder ones. Large files, small files.
Everything comes out null! Where have I gone wrong?
your names don't line up... you need to model bind your file control called "postedFile" in your controller
Try it like this:
#using (Html.BeginForm("uploadCustomImage", "W", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="fileToUpload" type="file" />
<input type="submit" />
}
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase fileToUpload)
{}
[EDIT]
I've just implemented an upload feature in a project I'm working on and it works.
#using (Html.BeginForm("Import", "MY_CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="UploadedXlsFile" name="UploadedXlsFile"/>
<input type="submit" id="Submit" name="Submit" value="Submit"/>
}
public ActionResult Import()
{
if (Request.Files["UploadedXlsFile"].ContentLength > 0)
{
.............Do stuff ................
}
}
The previous code works for me. If I put a break point inside the Action method, I can see the file isn't null.

uploading an image

Recently I am getting interested in image manipulation. But I am stuck just at the beginning of the long journey.
I have a problem in uploading an image in asp.net mvc3(razor view) project.
Can any one suggest me a basic sample/tutorial how to do it so.
To upload an image just call this in your html.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
Be sure to have enctype = "multipart/form-data" or your file won't be uploaded.
Then from the controller just handle the Request.Files of accept directly a HttpPostedFileBase
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//file handling logic
file.SaveAs(/* your path here */);
}
return RedirectToAction("Index");
}
Remember also that classic file upload don't work with ajax calls. If that is the case you must use a plugins like this one

Categories

Resources