How do I upload images in ASP.NET MVC? - asp.net-mvc

How do I upload images to go into ~/Content/Images in ASP.NET MVC 3.0?

HTML Upload File ASP MVC 3.
Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML View:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.File, new { type = "file" })
#Html.ValidationMessageFor(m => m.File)
}
Controller action:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}

If you want to upload images in ASP.NET MVC, try these questions:
Simple Image Upload in ASP.NET MVC
Uploading an image in ASP.NET MVC
If you're wanting to use an ASP.NET control to upload images, that breaks the separation of concerns for MVC. There are upload helpers available.

Related

File Upload as Part of Form with Other Fields

I have an ASP.NET MVC website. I need a page where the user must enter several fields, including an image file.
I could find many, many references for uploading a file using MVC. But they don't upload the file as part of a form with other fields.
Ideally, fields and file will be sent to a single controller. Any tips?
If you do not use third party libraries, try this:
Model
public class Strategy
{
public int ID { get; set; }
public string Name { get; set; }
public byte[] File { get; set; }
}
View
#model TEST.Model.Strategy
#using (Html.BeginForm("Add", "Strategy", FormMethod.Post, new { #id = "frmStrategy", enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(x => x.Name)
<input id="templateFile" name="templateFile" type="file" />
#Html.HiddenFor(x => x.ID)
}
Controller
[HttpPost]
public ActionResult Add(Strategy model, HttpPostedFileBase templateFile)
{
if (templateFile != null && templateFile.ContentLength > 0)
{
try
{
var fname = Path.GetFileName(templateFile.FileName);
using (MemoryStream ms = new MemoryStream())
{
templateFile.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
model.File = array;
}
...
You can use FineUploader. See Demo
Valums Uploader. It uses pure Javascript (uploads file using Iframe)
You might need to use a client plugin. Plupload is one possible choice. And here's an example of how you could integrate it in your MVC application. Another popular plugin which supports this functionality is Uploadify.
Asp.net mvc 3 file uploads using the fileapi
See Progress Demo 1, 2 & 3 at http://jquery.malsup.com/form/#file-upload
Ref: http://forums.asp.net/t/1897410.aspx/1?MVC4+File+Upload

Uploading Files into Database with ASP.NET MVC

I want to give a facility on my form for user to upload files and save in Database.
How is this done in ASP.NET MVC.
What DataType to write in my Model Class. I tried with Byte[], but during the scaffolding the solution could not generate the appropriate HTML for it in the corresponding View.
How are these cases handled?
You could use a byte[] on your model and a HttpPostedFileBase on your view model. For example:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
and then:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
byte[] uploadedFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
// now you could pass the byte array to your model and store wherever
// you intended to store it
return Content("Thanks for uploading the file");
}
}
and finally in your view:
#model MyViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
#Html.LabelFor(x => x.File)
#Html.TextBoxFor(x => x.File, new { type = "file" })
#Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">Upload</button>
}

Asp.Net MVC Razor FileUpload Html Helper into existing View

I have have a View where I add products to a simple WebStore. I want to have multiple images with one product. That's why I use FileUpload from Microsoft.Web.Helpers. The use of FileUpload in my View is like this:
#FileUpload.GetHtml("Upload", 5, true, true, addText: "Add more", uploadText: "Upload files")
Then I have some labels and fields for other product attributs like this:
<div class="editor-field"><br>
#Html.EditorFor(model => model.Title)<br>
#Html.ValidationMessageFor(model => model.Title)<br>
</div>
The problem is that when I use post method, my controller does not get anything. I use controller like this:
[HttpPost]
public ActionResult Create(Product product, IEnumerable<HttpPostedFileBase> fileUpload)
{
foreach (var file in fileUpload)
{
var fileName = Path.GetFileName(file.FileName);
}
return RedirectToAction("Index");
}
So does anyone have any idea what I am doing wrong. Because my FileUpload object is always empty.
Most likely your BeginForm is missing the required field. It should look like this:
using(Html.BeginForm("Index", "Home", FormMethod.Post,
new { enctype="multipart/form-data" })) {
}
Now using HttpPostedFileBase in mvc 4 easy to upload multiple files, EditorFor FileUpload in asp.net mvc 4 razor
I had this problem last night FileUpload control and the parameter name should be the same
Change:
public ActionResult Create(Product product, IEnumerable<HttpPostedFileBase> **fileUpload**)
to
public ActionResult Create(Product product, IEnumerable<HttpPostedFileBase> **upload**)

MVC - file upload

Hey...
I have upload control on my view. Is there a way to associate this control with model data(something like LabelFor or TextBoxFor). I need this, because on page load I loose my information in file upload control
Thx
HTML Upload File ASP MVC 3.
Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML View:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.File, new { type = "file" })
#Html.ValidationMessageFor(m => m.File)
}
Controller action:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
Yes, use the HttpPostedFileBase class for the property type and it will bind just like any other property would.

Binding HttpPostedFileBase using Ajax.BeginForm

I have a form which binds a model and a file upload using the default binder for HttpPostedFileBase.
This works fine when using Html.BeginForm(). However, I wanted to perform the same action using AJAX so I replaced this with Ajax.BeginForm() changing the parameters accordingly.
The model still binds correctly, however I can't get the file upload to bind to the HttpPostedFileBase.
This binds the model and the file upload:
<% using (Html.BeginForm("MapUpdateColumns", "RepositoryAdmin", FormMethod.Post, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>
This only binds the model:
<% using (Ajax.BeginForm("MapUpdateColumns", "RepositoryAdmin", new AjaxOptions { UpdateTargetId = "columnMappings" }, new { id = "UpdateDataset", enctype = "multipart/form-data" })) {%>
The controller action:
public ActionResult MapUpdateColumns(DatasetViewModel model, HttpPostedFileBase sourceFile)
Should this be possible, and if so what am I doing wrong? Thanks.
You cannot upload files with AJAX. One way to achieve this is to use a hidden iframe which will simulate an AJAX call and perform the actual file upload or use Flash. Here's a very nice jQuery Form plugin using a hidden iframe which is capable of transparently ajaxifying a form submission containing file fields.
It is possible, the answer is here:
https://stackoverflow.com/a/13522052/1067149
I did it myself and it's guaranteed it works.
ADD id="file" in your tag input
IN YOUR ACTIONRESULT PARAMETER
HttpPostedFileBase 'file' name and view tag name should be same
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(tbl_products tbl_products,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
tbl_products.phototype = file.ContentType;
tbl_products.photo =new byte[file.ContentLength ];
file.InputStream.Read(tbl_products.photo,0, file.ContentLength);
if(obj.insert(tbl_products))
{
return RedirectToAction("Index");
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
}
return View(tbl_products);
}
IT WORKS FOR ME
Yes I also agree. You can definately upload files using 'Ajax.BeginForm'.Add 'enctype = "multipart/form-data"' to the AjaxOptions object.

Resources