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();
}
Related
I have a View which displays a list of file names. Also i have two buttons called View and Release. When I select a file name from the list and click on view, it navigates to the appropriate action method along with the file name selected as a parameter and performs the functionality as required.
But when i click on Release after selecting a file name, it does navigates to the appropriate action method, but does not passes the file name as a parameter to the action method. It shows as null.
Please note that View and Release directs to a single controller having different action methods.
How can i get to pass the filename as a parameter when i click on release?
Please see the code below:
public class HoldFilesController : Controller
{
// GET: HoldFiles
string holdpath = ConfigurationManager.AppSettings["HoldPath"].ToString();
public ActionResult Index()
{
DirectoryInfo dirInfo = new DirectoryInfo(holdpath);
List<FileInfo> files = dirInfo.GetFiles().ToList();
return View("Index",files);
}
}
[HttpPost]
public ActionResult ViewFile(string[] Name)
{
byte[] ImageData = null;
for (int i = 0; i < Name.Length; i++)
{
string filepath = holdpath + #"\" + Name[i];
FileStream fs = new FileStream(filepath, FileMode.Open,
FileAccess.ReadWrite);
ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
}
return File(ImageData,"application/pdf");
}
[HttpPost]
public ActionResult ReleaseFile(string[] Name)
{
for(int i=0; i<Name.Length;i++)
{
string sourcefilepath= holdpath + #"\" + Name[i];
string Destinationfilepath =
ConfigurationManager.AppSettings["ReleaseFolderPath"].ToString();
string ReleaseFilePath = Destinationfilepath + #"\" + Name[i];
if (Directory.Exists(Destinationfilepath))
{
System.IO.File.Move(sourcefilepath, ReleaseFilePath);
}
}
return RedirectToAction("Index");
}
Here's the code for my view:
#model IEnumerable<FileInfo>
#{
ViewBag.Title = "files";
}
<h2>Held files</h2>
#using (Html.BeginForm())
{
<div style="border:solid;width:100%;overflow-x:auto;">
<table align="center" style="width:100%">
<thead>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (FileInfo file in Model)
{
<tr>
<td>
<input type="checkbox" name="Name" value="#file.Name" />
#file.Name
</td>
</tr>
}
</tbody>
</table>
</div>
<input type="submit" id="Held" name="Held file" value="View" />
<input type="submit" id="Release" name="release" value="Release" />
}
Just to avoid confusion, the View button redirects to the ViewFile method
and the Release button redirects to Releasefile method.
You have multiple options to do this.
You can hijack the submit button click and update the form action attribute value based on what button is clicked and do the form submit using javascript.
You can keep the url to the 2 action methods in html5 data attributes on the button.
<input type="submit" data-myaction="#Url.Action("View")" value="View"/>
<input type="submit" data-myaction="#Url.Action("Release")" value="Release"/>
Using the Url.Action method to generate the correct relative path to the action method is a safe practice. Let the method worry about generating the correct path for you.
And the javascript
$(function () {
$("input[data-myaction]").click(function(e) {
e.preventDefault(); // stop the normal form submit
// read the data attribute and update the forms action and do a submit
$(this).closest("form").attr('action', $(this).data('myaction')).submit();
});
});
Another option is using html5 formaction which does not need any javascript hijacking. When you specify a formaction attribute value, it will override the parent form's action attribute. this is very useful when you have more than one submit button with 2 different action methods to submit to (your use case)
<input type="submit" formaction="#Url.Action("View")" value="View"/>
<input type="submit" formaction="#Url.Action("Release")" value="Release"/>
1-HTML5 formaction and formmethod attributes
<input type="submit" name="view" value="view" formaction="ViewFile" formmethod="post" />
<input type="submit" name="Release" value="Release" formaction="ReleaseFile" formmethod="post" />
2-jQuery / JavaScript code
$(document).ready(function () {
$("#Held").click(function () {
$("form").attr("action", "/HoldFiles/ViewFile");
});
$("#Release").click(function () {
$("form").attr("action", "/HoldFiles/ReleaseFile");
});
});
I have three page, It all contain a PartialView that is a member data info panel.
That PartialView can change Photo using Html.BeginForm.
But I face the problem with when I Submit Photo, It can't return to same page.
How to solved it ?
Code:
View(Page,have three diffrent page , but all have same PartialView):
<div>Page 1</div>
<div class="sidebar">
#Html.Action("_MemberInfoPartial")
</div><!-- END sidebar-->
<div>blah blah ... </div>
View(Partial):
<figure class="cropper">
<a>#Model.UserName</a>
<img src="#Model.Image" class="photo">
<figcaption>Select Pic</figcaption>
#using (Html.BeginForm("UploadIcon", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file" class="temp-icon-file" />
<input type="submit" name="submit" value="Submit" class="temp-icon-submit" />
}
<script>
$(function () {
$('.cropper figcaption a').click(selectFile);
$('.temp-icon-file').change(uploadFile);
});
function selectFile() {
$('.temp-icon-file').click();
}
function uploadFile() {
var val = $('.temp-icon-file').val().toLowerCase().split('.');
if (val.length > 0) {
var ext = val[val.length - 1];
if (ext === 'jpg' || ext === 'png') {
$('.temp-icon-submit').click();
return;
}
}
}
</script>
</figure>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadIcon(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//Upload Image
}
else
TempData["TempMessage"] = "Please Select Picture! (jpg/png)";
return RedirectToAction("Page1") <--How to return to same page(The Page I click upload, it can be page1 or 2 or 3)?
}
if you pass current action name when calling child action:
#Html.Action("_MemberInfoPartial", new { parentAction = ViewContext.RouteData.Values["action"] })
and in your child action, store it in ViewData:
public ActionResult _MemberInfoPartial(string parentAction)
{
//...
ViewBag.ParentAction = parentAction;
//...
}
to render parent action in a hidden field, for example:
#{
string parentAction = ViewBag.ParentAction;
}
#using (Html.BeginForm("UploadIcon", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="file" id="file" class="temp-icon-file" />
<input type="submit" name="submit" value="Submit" class="temp-icon-submit" />
#Html.Hidden("returnAction", parentAction)
}
you can use parent action upon form submit:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadIcon(HttpPostedFileBase file, string returnAction)
{
if (file != null && file.ContentLength > 0)
{
//Upload Image
}
else
TempData["TempMessage"] = "Please Select Picture! (jpg/png)";
return RedirectToAction(returnAction);
}
Pass a value to your controller to determine on what page you need to return.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadIcon(HttpPostedFileBase file, int returnId)
{
if (file != null && file.ContentLength > 0)
{
//Upload Image
}
else
TempData["TempMessage"] = "Please Select Picture! (jpg/png)";
if(returnId == 1)
return RedirectToAction("Page1");
//and so on..
}
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
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();
}
}