extracting files from request - c#

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.

Related

How to forward input file path and name in ASP?

I am trying to use ASP to upload a JSON file. However, for some strange reason, the control that I use for that only forwards the file name, but not the path.
Here's what I'm doing in my .cshtml:
<form asp-page-handler="AddDevices" method="post" >
<button
class="btn btn-default"
id="btn_add_devices"
>
Add Devices
</button>
<input type="file" name="fileNameAndPath" accept="application/JSON"/>
</form>
...and here's the function that gets called in the corresponding .cs:
public void OnPostAddDevices(string fileNameAndPath)
{
string jsonString = System.IO.File.ReadAllText(fileNameAndPath);
[Deserialization]
}
The problem is, that instead of the file name and path that I would like to arrive at that function, only the file name is passed on, so for example if I use the file selector to select the file C:/TestFiles/TestJson.json, then in the function OnPostAddDevices, the value of the parameter fileNameAndPath is only TestJson.json instead of what I would need C:/TestFiles/TestJson.json.
Naturally, that subsequently results in a FileNotFoundException.
What can I do to make the input pass on the full file name with path in this case?
Here's what I ended up doing now, and what worked to my satisfaction based on the following tutorial:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0
Summed up in short:
In my index.cshtml, I added this for the upload button:
<form enctype="multipart/form-data" method="post">
<dl>
<dt>
<label asp-for="FormFile"></label>
</dt>
<dd>
<input asp-for="FormFile" type="file">
</dd>
</dl>
<input asp-page-handler="UploadDeviceFile" class="btn" type="submit" value="Upload">
</form>
In my Index.cshtml.cs, I added this for the uploading logic:
[BindProperty]
public IFormFile FormFile { get; set; }
public async Task<IActionResult> OnPostUploadDeviceFileAsync()
{
using (var memoryStream = new MemoryStream())
{
await FormFile.CopyToAsync(memoryStream);
string jsonString = Encoding.ASCII.GetString(memoryStream.ToArray());
DeviceContainer deviceContainer = JsonConvert.DeserializeObject<DeviceContainer>(jsonString);
DatabaseController.AddAll(deviceContainer.Devices);
}
return Page();
}

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.

Upload multiple files where upload has ID

I have a page which has multiple file upload inputs whcih have ID's and Names relevant to the document type being uploaded which look like:
<input type="file" name="postedFile_37" id="37">
<input type="file" name="postedFile_23" id="23">
In my controller, how can I identify the name or id of the upload so I can assign a document to the type being uploaded in the DB?
I can see for example that if I do
Request.Files[i]
I can see the name of the index but I can't get the value to save out. How can I get either the name or ID from the posted file upload?
Try adding hidden fields next to each of the files so you have two arrays - first is file itself and second is id.
<input type="hidden" name="fileId" value="37" />
<input type="file" name="file" />
<input type="hidden" name="fileId" value="38" />
<input type="file" name="file" />
.
public ActionResult Test (string[] fileId, List<HttpPostedFileBase> file)
{
int i = 0;
foreach (var f in file)
{
var id = fileId[i]; // this is your file id, f is file
i++;
}
}
If you use the ASP.NET FileUpload control instead of the plain HTML control, you can access them individually (by ID) in the PostBack.

how to upload .txt files to sql database using asp.net(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();
}
}

Categories