File uploading in MVC 4 - asp.net-mvc

I simply tried this, but its not working, what is the problem in it,
MY index page:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/from- data" }))
{
<div>
<h1 style="align-content: center; color: blueviolet">Application to upload files</h1>
</div>
<div>
<input type="file" id="file" name="file" />
<br />
<input type="submit" id="load" name="submit" value="Submit" />
</div>
}
And My controller is,
[HttpPost]
public ActionResult Upload()
{
string path = #"~/Content/Upload";
HttpPostedFileBase file = Request.Files["file"];
if (file != null)
file.SaveAs(path + file.FileName);
return Content("Sucess");
}

The path you are attempting to save your file to looks wrong. Try with MapPath:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
string path = Server.MapPath("~/Content/Upload");
if (file != null)
{
file.SaveAs(Path.Combine(path, file.FileName));
}
return Content("Sucess");
}
Also make sure that you have used the correct enctype attribute in your form:
enctype = "multipart/form-data"
instead of:
enctype = "multipart/from- data"

Related

Request.Files.Count always 0 when using an input of type file

I am not able to get the uploaded file, it always shows Request.Files.Count as 0.
#using (Html.BeginForm("HandleForm", "Home", new { EncType = "multipart/form-data" }))
{
<div>Upload Something:
<input type="file" name="uploadedFile" />
</div>
<br/>
<input type="submit" value="Submit" />
}
Controller Action:
public ActionResult HandleForm(HttpPostedFileBase uploadedFile)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
return View("FormResults");
}
You are using the wrong overload of BeginForm() and adding a route value for enctype, not a html attribute.
You need to use this overload
#using (Html.BeginForm("HandleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))`

Multiple Action of Controller in single Button in MVC 4

my controller Have 2 Actions :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
//
// GET: /AdultLiteracyTeachers/Details/5
public ActionResult Details(int id = 0)
{
AdulLiteracyTeachers adulliteracyteachers = db.AdulLiteracyTeachers.Find(id);
if (adulliteracyteachers == null)
{
return HttpNotFound();
}
return View(adulliteracyteachers);
}
my view in Create.cshtml
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" }))
<input type="file" name="files" value="Upload Image" />
<input name="Upload" type="submit" value="Create" />
Problem is
only upload is working when I submit button others create etc not working
how to call multiple actions in single form create button ?
I believe you can use the beginform multiple times like this:
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="submit" name="files" value="Upload Image" />
}
#using (Html.BeginForm(Details, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input name="Upload" type="submit" value="Create" />
}
and make sure that the button type="submit".

How to pass other form data along with MVC File Upload?

I am trying to implement File Upload in MVC. I have the following code which works.
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
Now I want to add a dropdown box (to select the file type) and send that value along with the file to my Controller. How can I do that (send other form data along with the file)?
You should be able to add them to the view, include them in the POST and have MVC take care of the model binding:
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<select name="fileType">
<option value="JPG">Photo</option>
<option value="DOC">Word</option>
</select>
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string fileType)
{
//Validate the fileType
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
I ended up doing it as follows it as follows. works good for me:
Created a Model:
public class FeeUpload
{
[Required (ErrorMessage="File Type required")]
public string fileType { get; set; }
[Required (ErrorMessage="file required")]
public HttpPostedFileBase File { get; set; }
}
View:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(false, "Please fix the following:")
<div>
<div>
#Html.DropDownListFor(model => model.fileType,
new List<SelectListItem>
{
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" }
}, "Select")
#*#Html.ValidationMessageFor(model => model.fileType)*#
</div>
<div>
#Html.TextBoxFor(model => model.File, new { type = "file" })
#*#Html.ValidationMessageFor(model => model.File)*#
<input type="submit" value="OK" class="button" id="btnsubmit" />
</div>
</div>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeesAndCostsUpload(FeeUpload feeUploadFile)
{
if (ModelState.IsValid)
{
//do something with feeUploadFile.File and feeUploadFile.fileType
}
return View();
}
Try to not use Razor for the form
<form method="POST" data-url="#Url.Action("Action", "Controller")" enctype="multipart/form-data">
#Html.ValidationSummary(true)
<span class="btn btn-success fileinput-button">
<i class="fa fa-plus"></i>
<span>Add a file...</span>
#Html.TextBoxFor(model => model.Fichier, new { type = "file" })
</span>
<div class="form-group form-actions">
<div class="col-sm-offset-3 col-sm-9">
<input id="submit" type="submit" class="btn btn-primary" value='Value' />
</div>
</div>
</form>
worked for me

how do i refere my textbox of type file from view to controller

Im trying to upload an image to the database but i im getting an error with object refernece not set to an instance of an object.
i have a textbox in the view and im using memorystream in the controller but i cant store the image to the memorystream.
i also have a model where have this property
public HttpPostedFileBase file { get; set; }
heres the code from the view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
#Html.TextBoxFor(m => m.file, new { type = "file" })
#*<input type="file" value="file" />*#
<input type="submit" value="Create" />
</fieldset>
}
and this is the code from the controller:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
var memoryStream = new System.IO.MemoryStream();
file.InputStream.CopyTo(memoryStream);
var fileBytes = memoryStream.ToArray();
return RedirectToAction("Index");
}
add enctype attribute your form element
#using (Html.BeginForm("Create",
"Home",
FormMethod.Post,
new { id = "form", enctype="multipart/form-data" }))
{
}

MVC 3 input file always null

I added an input file field but it's always null on the controller. What am I missing?
Here's the code for both my view and controller.
view:
...
#using (Html.BeginForm())
{
...
<input type=file name="file" id="file" class="post-attachment" />
...
}
controller:
[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
// save file to server
if (file != null && file.ContentLength > 0)
{
var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
file.SaveAs(path);
}
...
}
You need to explicitly set the enctype of the form:
#using(Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
You need to change your form to something like -
#using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload"/>
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
There's a load more info (including the sample above) in this question - Html helper for <input type="file" />

Resources