How to upload file in ASP.NET razor - c#

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");
}

Related

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.

Cannot Upload image to server using asp.net mvc

I want to upload image to the server, The below code is working properly when i run the the code locally on my system, but when i upload it to the server it gives error message - The model item passed into the dictionary is of type 'Login.Models.User', but this dictionary requires a model item of type 'System.Collection.Generic.IEnumerable'[Login.Models.User]'.Please help to solve this issue.
public ActionResult FileUpload(HttpPostedFileBase file, Login.Models.User model)
{
if(ModelState.IsValid)
{
try
{
var user=db.User.FirstOrDefault(c=>c.Userid==model.Userid);
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/images/profile/"), pic);
file.SaveAs(path);
user.imagepath = "http://sampleApp.com/images/profile/" + pic;
}
Catch(Exception ex)
{
ModelState.AddModelError("",ex.Message);
}
return View("ViewAdmin",model);
}
db.ObjectStateManager.ChangeObjectState(user,System.Data.EntityState.Modified);
db.SaveChanges();
return RedirectToAction("User");
}
View
#model Login.Models.User
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}

file upload doesn't work in ASP.NET MVC4 - mobile template

I am using C# and ASP.NET MVC4 for a web application (mobile template).
Now I have the following code in my view:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file">Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" value="Upload" />
}
and this in my controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string path = System.IO.Path.Combine(Server.MapPath("~/Content"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
return View();
}
when I run the application and try to upload a file, I get
"Object reference not set to an instance of an object." message in Visual Studio.
But I know that the code above works fine in ASP.NET MVC3 as I've used it before.
Can anyone help me with this?
Add this attribute to your form: data-ajax="false"
#using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype="multipart/form-data", data_ajax="false"})){
<label for="file">Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" value="Upload" />
}
You don't have to use HttpPostedFileBase, as the matter of fact you don't have to receive any parameters in your [HttpPost] Action. You can get your file from the request like this as long as your form is set to enctype = "multipart/form-data" (which you already do):
var file = Request.Files[0];

mvc save file to folder in site

I'm trying to save files to a folder in my site, but I keep receiving an UnauthorizedAccessException error.
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
var img = Path.GetFileName(image.FileName);
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/Content/productImages/"),
System.IO.Path.GetFileName(image.FileName));
image.SaveAs(path);
product.ImageName = img;
}
// save the product
repository.SaveProduct(product);
// add a message to the viewbag
TempData["message"] = string.Format("{0} has been saved", product.Name);
// return the user to the list
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(product);
}
}
HERE IS THE VIEW
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" })) {
#Html.EditorForModel()
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.ImageName == null) {
#:None
} else {
<img width="150" height="150"
src="#Url.Action("GetImage", "Product", new { Model.ProductID })" />
}
<div>Upload new image: <input type="file" name="image" id="image"/></div>
</div>
<input type="submit" value="Save" />
#Html.ActionLink("Cancel and return to List", "Index")
}
I'm receiving the error on the image.SaveAs(path); line
I can't see what exactly I'm doing wrong. Any help?
Looks like a permission problem
Change the Permissions on productImages folder so that ASP.NET can write to that.

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