I am trying to build an image application in which user can upload an image on the server.
I am using HTML 5.0 as my front end and c# as my backend following an MVC 4 architecture. I will be attaching my code below.
<div id="imageup">
<form method="post" action="UploadImage" enctype="multipart/form-data">
<label for="file">Filename:</label>
Image: <input type="file" name="file" id="file"/>
NAME: <input type="text" name ="testname" id="nametestid" runat="server"/>
<input type="submit" value="image" />
</form>
</div>
Here is my backend code which I found on http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
Here is the back end code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(String testname)
{
Console.Out.WriteLine("HERE");
// name.Length
if(testname.Length==0){
System.Console.WriteLine("Hello");
//return Json("All files have been successfully stored.");
}
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
/* foreach (HttpPostedFile file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
}
//*/
return RedirectToAction("Create");
}
The issue with the code is when I pass file by browser, and in breakpoints I get the value of image as null, but I am getting the text which I have inputted in the same form as data.
Finally figured it out,
The point was to tell the controller that I am passing the image as part of form.
just had to add:
#using (Html.BeginForm("UploadImage", "Image", FormMethod.Post,
new { enctype = "multipart/form-data" }))
Thanks Mike & Tommy
Related
I try to insert image to server, in view i use mvc2, my code is:
<% using (Html.BeginForm("Upload", "Main", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%><br />
<input type="file" name="files" id="file1" size="25" />
<input type="submit" value="Upload file" />
<% } %>
In MainController I use:
[HttpPost]
public ActionResult Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Images")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}
}
But when i go on submit button nothing happen i try to debug and I see that public ActionResult Upload are not calling.
What can be problem?
Thanx
Your code would not compile, you need to return an ActionResult from within the action i.e.
[HttpPost]
public ActionResult Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Images")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}
// Below line is missing
return View();
}
I'm using ASP.net MVC 5.
The code below works to store files, but I need to store the request or extract the files uploaded from the request so I can pass the file to a method in another class for validation BEFORE I upload to the file server.
I noticed below that Request.Files[upload].SaveAs contains the files, but how do I pass the file to another class? I tried passing the HttpPostedFileBase File to another class, but it doesn't recognize Files.
In my view:
#using (Html.BeginForm("FileUpload",
"Upload",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ <label for="file">Upload Image:</label>
<input type="file" name="FileUpload" /><br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
My Controller:
public ActionResult FileUpload(HttpPostedFileBase file)
{
//HttpPostedFileBase request = file;
foreach (string upload in Request.Files)
{
System.Diagnostics.Debug.WriteLine("*********************savepath:" + Request.Files[upload].FileName+"********************");
string savePath = "C:\desktop";
string newPathForFile = Path.Combine(savePath, Path.GetFileName(Request.Files[upload].FileName));
Request.Files[upload].SaveAs(Path.Combine(savePath, newPathForFile));
}
return View("Home");
}
You can't really pass the "file," since at this point there really isn't a file. We're really looking at a bunch of bytes. Your Request.Files should also have an InputStream. Use that to copy the file to a Byte[] buffer, and go from there.
I'm attempting upload multiple files in ASP.NET MVC and my controller is
public ActionResult GalleryAdd()
{
foreach (string fil in Request.Files)
{
HttpPostedFileBase file = Request.Files[fil];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Gallery"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
And my input field is
<input type="file" id="files" name="files" multiple>
Problem is that always upload only one file(first file) . Foreach loop only take the first file , but Request.Files Count shows number of file uploaded. What is the problem here
Change the signature of your GalleryAdd action to take an IEnumerable of HttpPostedFileBase, then you can iterate over the files passed in from the view:
public ActionResult GalleryAdd(IEnumberable<HttpPostedFileBase> files)
{
foreach (string file in files)
{
//iterate over files
}
}
Then add a file input for each file to add:
<form action="#Url.Action(GalleryAdd)" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
you can write webservice that will be called in controller.
use this link for getting help regarding upload file
also look in this link.
I am saving image files in a folder /images/profile and i want to save the image path in a database and do not know how to display image in a view. I am new to MVC. Following are the codes for image uploading. Please help.
HomeController.cs
public class HomeController : Controller
{
ImageEntities db = new ImageEntities();
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
}
return View("FileUploaded", db.tbl_Image.ToList());
}
public ActionResult FileUploaded()
{
return View();
}
}
FileUpload.cshtml
#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" />
}
FileUploadedView.cshtml
#foreach (var item in Model)
{
<img src="~/images/profile/#item.imagepath" />
}
You shoud save image name instead of image path in table.
Then in view try this:
<img src="~/images/profile/#Model.imageUrl" />
"Update"
See here:
How to save image in database and display it into Views in MVC?
save the image path like this: "~/images/profile/mypic.jpg"
and then in you view:
<img src="#Url.Content("~/images/profile/mypic.jpg")" />
or in case you have a Photo class: (consider "item" as your image)
<img src="#Url.Content(item.Path)" />
thats it.
According to the suggestion of Samiey Mehdi I did this at my code for making it work
In the Controller:
newRecord.flName = ImageName;
In the View:
<img src="~/images/#item.flName" width="100" height="100" />
how to upload .txt files to sql database using asp.net(C#)
Is this something that will be done manually by a user?
If so, how about an ASP.NET MVC application?
In your View:
<h2>
Upload A File of Foos</h2>
<%
Html.BeginForm("LoadFoos", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" });
%>
<label for="foosFile">
Foos file:
</label>
<input type="file" name="FileUpload1" id="foosFile" /><br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
<%
Html.EndForm();
%>
In your Controller:
public class AdminController : Controller
{
public ActionResult LoadFoos()
{
if (Request.Files.Count > 0)
{
// This illustrates how to read the uploaded file contents,
// and would need to be adapted to your scenario
List<string> foos = new List<string>();
using (StreamReader reader = new StreamReader(Request.Files[0].InputStream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
foos.Add(line);
}
}
// TODO: use LINQ 2 SQL, NHibernate or ADO.NET to load the foos directly,
// or call a web/WCF service behind your firewall that does this
}
return View();
}
}