Can't convert HttpFileCollectionBase to HttpFileCollection - asp.net-mvc

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

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" />
}

#Html.DisplayFor() value not change after the postback

#Html.DisplayFor() value not change after send data. I read a article about this issue and say it like this; only send data what such as EditorFor, TextBoxFor, TextAreaFor and change state. Is it true? How can I change this value after the postback?
View
#model HRProj.Model.Person
#using(Html.BeginForm("Skills", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m => m.SkillDoc.Filename)
<span class="file-upload">
<span>Choose a file</span>
<input type="file" name="file" />
</span>
File name : #Html.DisplayFor(m => m.SkillDoc.Filename)
<button>Upload</button>
}
Controller
public ActionResult Skills(int? id)
{
Others oparations...
var model = new Person { SkillDoc = db.GetSkillDoc().FirstOrDefault(m => m.PersonId == id) };
return View(model);
}
[HttpPost]
public ActionResult Skills(Person model, HttpPostedFileBase file)
{
Others oparations...
if (ModelState.IsValid)
{
SkillDoc doc = new SkillDoc();
doc.Id = model.SkillDoc.Id;
doc.PersonId = model.SkillDoc.PersonId;
doc.CvDoc = (file != null) ? file.FileName : model.SkillDoc.CvDoc;
db.SkillDocCRUD(doc, "I");
TempData["eState"] = "The record adding successfully";
if (file != null)
{
file.SaveAs(Server.MapPath("~/Files/" + file.FileName));
}
}
return View(model);
}
Please add the following line inside the if block:
model.SkillDoc=doc;
Or rather redirect to Skills action:
return RedirectToAction("Skills", new{id= model.PersonId});

file upload with MVC application

I am trying to add file upload to my asp.net mvc4, however, since I am just learning C# I am not sure on how where to add it:
This is the controller:
public ActionResult Create()
{
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View();
}
//
// POST: /Create
[HttpPost]
public ActionResult Create(TotalReport treport)
{
if (ModelState.IsValid)
{
treport.created = DateTime.Now;
db.TotalReports.Add(treport);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View(treport);
}
the view is here:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="mycss">
<input type="file" name="file" />
</div>
</fieldset>
ok here is the part that saves the file:
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = System.IO.Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = System.IO.Path.Combine(Server.MapPath("~/myfolder"), fileName);
file.SaveAs(path);
}
Suppose if your markup is like,
<input type="file" name="file" />
and then your action should look like,
[HttpPost]
public ActionResult(HttpPostedFileBase file)
{
string filename=file.FileName;
filename=DateTime.Now.ToString("YYYY_MM_dddd_hh_mm_ss")+filename;
file.SaveAs("your path"+filename);
return View();
}
here parameter name of HttpPostedFileBase and upload control name should be same. Hope this helps
pick up the files in the controller like so
[HttpPost]
public ActionResult Create(HttpPostedFileBase fileUpload)
{
if (ModelState.IsValid)
{
treport.created = DateTime.Now;
db.TotalReports.Add(treport);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.c_id = new SelectList(db.Cities.OrderBy(o => o.name), "c_id", "name");
ViewBag.m_id = new SelectList(db.Schools, "m_id", "name");
return View(treport);
}
just add argument for the posted file to your action :
public ActionResult Create(TotalReport treport, System.Web.HttpPostedFileBase file)
and do whatever you want to do with it - read stream, save it somewhere...

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

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.

Resources