File Upload in asp.net mvc3 - asp.net-mvc

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

Related

MVC File upload Where to put code

OK, so I am trying to make the move to MVC.
I have a Model, view and Controller made, but now I want to change the create functionality of the app.
I am working with uploads and I have this system generated code in my contoller.
Function Create(<Bind(Include:="Id,Course,Category,SubCategory,FileName,FileType,UploadedBy,DateUploaded")> ByVal acAsset As acAsset) As ActionResult
If ModelState.IsValid Then
db.Assets.Add(acAsset)
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View(acAsset)
End Function
Now I want to change this so that it will
Check for the existence of a folder for Course, Category and Sub category. If this folder is not there it must be created.
Upload the file select by a file selection box.
Post the files' name to the db.
The code is not necessarily the issue, I am jut not sure where I should put in the controller?
I have read this article but is not dealing with the DB post.
Thank you in advance.
You just add your code in controller that you want to hit on button click
Your Razor View Code
#using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
C# Code
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return RedirectToAction("UploadDocument");
}
}
In your View
<input type="file" name="file">
In your Controller
public actionresult(HttpPostedFileBase file)
{
string filename = Path.GetFileName(file.FileName);
string contentType = file.ContentType;
using (Stream fs = file.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
}
}
//Data Context Code here
tableName.File= bytes;
db.add(tableName);
db.SaveChanges();
}

ASP MVC HttpPostedFileBase always returns null

I have this code in my HomeController
[HttpPost]
public ActionResult NewRequest(int? id, FormCollection form, HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(uploadFile.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/Documents/Files"), fileName);
uploadFile.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
And my NewRequest view is this
#using (Html.BeginForm("NewRequest", "Controllers", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
}
The problem is that the uploaded file, .txt file f.x. is always null.
Your given code is fine. The only case I can think otherwise is you route config is probably not right.
I've tested with this config and it worked like a charm.
routes.MapRoute(
name: "NewRequest",
url: "Controllers/NewRequest",
defaults: new { controller = "Controllers", action = "NewRequest" }
);

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...

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

File upload 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....;
}
}

Resources