File upload MVC - asp.net-mvc

With the following markup in my view:
<form action="Categories/Upload" enctype="multipart/form-data" method="post">
<input type="file" name="Image">
<input type="submit" value"Save">
</form>
And in my controller:
public ActionResult Upload(FormCollection form)
{
var file = form["Image"];
}
The value of file is null.
If I try it in a different view using a different controller Controller and it works with the same code.
I have VS2008 on Vista, MVC 1.0.
Why?
Malcolm

Use HttpPostedFileBase as a parameter on your action. Also, add the AcceptVerb attribute is set to POST.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(HttpPostedFileBase image)
{
if ( image != null ) {
// do something
}
return View();
}
This code is quite in the spirit/design of ASP.NET MVC.

Not to be picky here or anything, but here's how the code ought to look, as Daniel is missing a few minor details in the code he's supplied...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadPlotImage(HttpPostedFileBase image)
{
if ( image != null )
{
// do something
}
return View();
}

Try this code:
public ActionResult Upload()
{
foreach (string file in Request.Files)
{
var hpf = this.Request.Files[file];
if (hpf.ContentLength == 0)
{
continue;
}
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "PutYourUploadDirectoryHere");
savedFileName = Path.Combine(savedFileName, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
...
}

Even I was facing a problem , The value was null in image at
public ActionResult UploadPlotImadge(HttpPostedFileBase image)
Earlier I didn't add [AcceptVerbs(HttpVerbs.Post)] which I added. Even after adding it, it didn't work because the second part I was missing, enctype="multipart/form-data", needed to be in the form tag ..
Now it works for me ....

try this class and below action and fix folder path in AppSetting.
config:
<appSettings>
<add key="UploadFolerPath" value="..Your folder path" />
</appSettings>
view:-
<form action="Account/AddImage" id="form_AddImage" method="post" enctype="multipart/form-data">
<input type="file" id="Img" name="Img" class="required" />
<input type="submit" value="Upload" id="btnSubmit" />
</form>
Class:-
public class FileUpload
{
public string SaveFileName
{
get;
set;
}
public bool SaveFile(HttpPostedFileBase file, string FullPath)
{
string FileName = Guid.NewGuid().ToString();
FileName = FileName + System.IO.Path.GetExtension(file.FileName);
SaveFileName = FileName;
file.SaveAs(FullPath + "/" + FileName);
return true;
}
}
//Post Action
[HttpPost]
public ActionResult AddImage(FormCollection Form)
{
FileUpload fileupload = new FileUpload();
var image="";
HttpPostedFileBase file = Request.Files["Img"];
if (file.FileName != null && file.FileName != "")
{
if (upload.ContentLength > 0)
{
fileupload.SaveFile(Request.Files["Img"], Server.MapPath(AppSetting.ReadAppSetting("UploadFolerPath")));
image = fileupload.SaveFileName;
// write here your Add/Save function
return Content(image);
}
}
else
{
//return....;
}
}

Related

File Upload in asp.net mvc3

I'm currently using Entity Framework Code First approach for my asp.net MVC3(aspx syntax) project.
I have a model in my project called EmployeeModel
public class EmployeeModel
{
public string imageinfo;
public string fileinfo;
}
My DbContext is
public class ContextDB:DbContext
{
public DbSet<EmployeeModel> Employee { get; set; }
}
I would like to have a file browser for both fileinfo and imageinfo in my view to upload the files and images and the path of the files and images need to be stored in the database.
Can anyone please help?
Try using
.chtml
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[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);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
Controller :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null) // file here will have your posted file which you post from view
{
int byteCount = file.ContentLength; <---Your file Size or Length
byte[] yourfile = new byte[file.ContentLength];
file.InputStream.Read(yourfile , 0, file.ContentLength);
var doc1 = System.Text.UnicodeEncoding.Default.GetString(empfile);
// now doc1 will have your image in string format and you can save it to database.
}
}
View :
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}

File Uploading in Asp.Net MVC

I am trying to make a file uploading page in my MVC project. First of all i want to manage this locally.
My Questions are:
1- Here is my controller and view. Is there any thing that I have to do to make this code work? I mean defining a model or using jquery, etc. What is the process when a file is being uploaded?
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("C:/Users/marti/../PhotoGallery/myimages"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Here is the View:
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
2- When i debug this, It never goes to controller.
You may need the enctype='multipart/form-data' on your view form:
#model ImageModel
#{
ViewBag.Title = "New Image";
}
<div class="content-form-container width-half">
<form id='PropertiesForm' action='#Url.Action(ImageController.Actions.Add, ImageController.Name)' method='post' enctype='multipart/form-data' class='content-form'>
#Html.Partial("ImageName")
<fieldset class='content-form-1field'>
<div class='legend'>
file to upload
</div>
#Html.LabelledFileInput(ImageView.FileName, string.Empty)
</fieldset>
<div class='buttons'>
#Html.Button("button-submit", "submit")
</div>
</form>
</div>
#section script{
#Html.JavascriptInclude("~/js/image/new.min.js")
}
And here is my controller code:
[HttpPost]
[MemberAccess]
public ActionResult Add()
{
var name = ImageView.ImageName.MapFrom(Request.Form);
if (Request.Files.Count == 0)
{
RegisterFailureMessage("No file has been selected for upload.");
return ValidationFailureAdd(name);
}
var file = Request.Files[0];
if (file == null || file.ContentLength == 0)
{
RegisterFailureMessage("No file has been selected for upload or the file is empty.");
return ValidationFailureAdd(name);
}
var format = ImageService.ImageFormat(file.InputStream);
if (format != ImageFormat.Gif && format != ImageFormat.Jpeg && format != ImageFormat.Png)
{
RegisterFailureMessage("Only gif, jpg and png files are supported.");
return ValidationFailureAdd(name);
}
if (query.HasName(name))
{
RegisterFailureMessage(string.Format("Image with name '{0}' already exists.", name));
return ValidationFailureAdd(name);
}
using (var scope = new TransactionScope())
{
var id = Guid.NewGuid();
var fileExtension = ImageService.FileExtension(format);
Bus.Send(new AddWikiImageCommand
{
Id = id,
Name = name,
FileExtension = fileExtension
});
var path = Path.Combine(ApplicationConfiguration.MediaFolder,
string.Format("{0}.{1}", id.ToString("n"), fileExtension));
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
file.SaveAs(path);
scope.Complete();
}
return RedirectToAction(Actions.Manage);
}
There are some custom bits in there so you can ignore those. The gyst of what you need should be there.
HTH

Forms collection does not contain input file (ASP.Net MVC 3)

#using (Html.BeginForm("Edit", "MyController", FormMethod.Post, new { enctype="multipart/form-data"}))
{
#Html.EditorFor(model => model.Name)
<input type="file" name="fileUpload" id="fileUpload" />
<input type="image" name="imb_save" src="/button_save.gif" alt="" value="Save" />
}
Submitted form and model are passed in this action:
[HttpPost]
public ActionResult Edit(MyModel mymodel, FormCollection forms)
{
if (string.IsNullOrEmpty(forms["fileUpload"]))
{
//forms["fileUpload"] does not exist
}
//TODO: something...
}
Why does not forms contain fileUpload? But it contains other inputs. How can I get content of my uploader?
Thanks.
Take a look at the following blog post for handling file uploads in ASP.NET MVC. You could use HttpPostedFileBase in your controller instead of FormCollection:
[HttpPost]
public ActionResult Edit(MyModel mymodel, HttpPostedFileBase fileUpload)
{
if (fileUpload != null && fileUpload.ContentLength > 0)
{
// The user uploaded a file => process it here
}
//TODO: something...
}
You could also make this fileUpload part of your view model:
public class MyModel
{
public HttpPostedFileBase FileUpload { get; set; }
...
}
and then:
[HttpPost]
public ActionResult Edit(MyModel mymodel)
{
if (mymodel.FileUpload != null && mymodel.FileUpload.ContentLength > 0)
{
// The user uploaded a file => process it here
}
//TODO: something...
}

MVC 3 - Image upload fails

I am trying write a program that allows users add a image to a database, but it fails. I would be grateful if someone could help me...
My Index.cshtml file has the following code...
<td>
#item.Picture1
<img alt="#Html.Encode(item.Picture1)" src='#(Url.Action(("Picture1")) +
ToString())' width="64" height="64" />
</td>
Create.cshtml file looks like this...
<div class="editor-field">
#Html.EditorFor(model => model.Picture1)
<input type="file" id="fileUpload" name="fileUpload" size="23"/>
#Html.ValidationMessage("Picture1", "*")
</div>
<p>
<input type="submit" value="Create" />
</p>
In the controller, for Create, I have the following code...
[HttpPost]
public ActionResult Create([Bind(Exclude = "SubProductCategoryID")] SubProductCategory2 Createsubcat2, FormCollection values)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
Createsubcat2.Picture1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[0]);
}
db.AddToSubProductCategory2(Createsubcat2);
db.SaveChanges();
return RedirectToAction("/");
}
PopulateProductCategoryDropDownList(Createsubcat2.ProductCategoryID);
return View(Createsubcat2);
}
public FileResult Image(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
SubProductCategory2 product = db.SubProductCategory2.Where(k => k.SubProductCategoryID == id).FirstOrDefault();
MemoryStream stream;
if (product != null && product.Picture1 != null)
{
stream = new MemoryStream(product.Picture1);
}
else // If product cannot be found or product doesn't have a picture
{
stream = new MemoryStream();
var path = Server.MapPath(alternativePicturePath);
var image = new System.Drawing.Bitmap(path);
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream, "image/jpeg");
}
FileHandler.cs
public class FileHandler
{
/// <summary>
/// Converts a HttpPostedFileBase into a byte array
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
{
int nFileLen = file.ContentLength;
byte[] result = new byte[nFileLen];
file.InputStream.Read(result, 0, nFileLen);
return result;
}
Thanks in advance. I am using http://blog-dotnet.com/category/ASPNET-MVC.aspx website for reference. I am using VS 2010, ASP.NET 4.0, MVC 3 in C#. SQL Server 2008R2. SubProductCategory2 table has file Picture1, image data type.
Edit:
Actually working on more I have public byte[] Picture1 { get; set; } in one of the classes. The output I am now getting is System.Byte[] System.Byte[]. How do I fix this?
As well as having an input with a type of file, you need to make sure your form accepts multipart data...
<form method="POST" enctype="multipart/form-data" action="">
I couldn't see your form element to confirm whether you had done this.

Can't convert HttpFileCollectionBase to HttpFileCollection

I have a partial view:
<% using (Html.BeginForm("add", "home", FormMethod.Post,
new { enctype = "multipart/form-data" })){%>
<input name="IncomingFiles" type="file" />
<div class="editor-field"><%: Html.TextBox("TagsInput") %></div>
<p><input type="submit" value="Create" /></p><% } %>
And this in the controller:
[HttpPost]
public ActionResult add(HttpFileCollection IncomingFiles, string TagsInput)
{
return View();
}
It will simply not match up my uploaded file to the HttpFileCollection, they come out as HttpFileCollectionBase.
How can i get the view to pass me a HttpFileCollection?
Do i need any specific BeginForm args?
Thank you!
Do something like this instead on your action side. You don't pass the files as parameters:
[HttpPost]
public ActionResult add(string TagsInput) {
if (Request.Files.Count > 0) {
// for this example; processing just the first file
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength == 0) {
// throw an error here if content length is not > 0
// you'll probably want to do something with file.ContentType and file.FileName
byte[] fileContent = new byte[file.ContentLength];
file.InputStream.Read(fileContent, 0, file.ContentLength);
// fileContent now contains the byte[] of your attachment...
}
}
return View();
}

Resources