how to upload .txt files to sql database using asp.net(C#) - c#

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

Related

Passing same parameter to an action on clicking two different buttons

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

extracting files from request

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.

uploading image to server using HTML5.0 with c# backend

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

Multiple file upload using single input controller

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.

How to display saved image in a folder in ASP.net MVC

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

Categories