I'm attempting to read an uploaded file from a multi-part form:
<form action="http://localhost:17034/api/v1/reports/create" method="post" enctype="multipart/form-data">
<input type="text" name="myFile" id="myFile" /><br />
<input type="text" name="Description" id="Description" /><br />
<input type="file" name="Content" id="content" />
<input type="submit" value="Submit" />
</form>
My controller action looks like:
[HttpPost]
[Route("reports/create")]
public async Task<HttpResponseMessage> Create()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (HttpContent ctnt in provider.Contents)
{
//I want to ensure I read text files as a stream so want
//to check the file extension
var fileName = ctnt.Headers.ContentDisposition.FileName //NULL FOR FILE INPUT
}
If I check the content disposition for the file input when I submit my form, I get this:
{form-data; name="myFile"}
CreationDate: null
DispositionType: "form-data"
FileName: null
FileNameStar: null
ModificationDate: null
Name: "\"myFile\""
Parameters: Count = 1
ReadDate: null
Size: null
dispositionType: "form-data"
parameters: Count = 1
{form-data; name="myFile"}
Name: "\"myFile\""
This is because you're checking the form data with the name myFile. You should be checking the one with the name Content:
Related
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();
}
In a Asp.net MVC view, i created a form, with a input field.
The user Sets a first name (or part of it), presses the submit button.
This is the form section:
<div>
<form action="SearchCustomer" methos="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
This is the SearchCustomer in the Controller, that gets the data from the form:
CustomerDal dal = new CustomerDal();
string searchValue = Request.Form["txtFirstName"].ToString();
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
When i run the program, and enter a first name ("Jhon" for example), the code returns to SearchCustomer function, but Request.Form is empty.
Why?
Thanks.
Your method is spelled wrongly should not read methos but method like below:
<form action="SearchCustomer" method="post">
....
</form>
You need to modify your code:
you need to provide a action name here, which should be defined in your controller(SearchController) with the same name as 'ActionName' you will put in the below code.
if SearchController is your action name then provide the controller in which the action is available.
<div>
<form action="SearchCustomer/<ActionName>" method="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
With Html.BeginForm :
#using (Html.BeginForm("<ActionName>","<ControllerName>", FormMethod.Post))
{
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
}
Set [HttpPost] on your controller.
[HttpPost]
public ActionResult SearchFunction(string txtFirstName)
{
CustomerDal dal = new CustomerDal();
string searchValue = txtFirstName;
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
}
If you View is the same name as your ActionResult method, try this:
#using(Html.BeginForm())
{
... enter code
}
By default, it'll already be a POST method type and it'll be directed to the ActionResult. One thing to make sure of: You will need the [HttpPost] attribute on your ActionResult method so the form knows where to go:
[HttpPost]
public ActionResult SearchCustomer (FormCollection form)
{
// Pull from the form collection
string searchCriteria = Convert.ToString(form["txtFirstName"]);
// Or pull directly from the HttpRequest
string searchCriteria = Convert.ToString(Request["txtFirstName"]);
.. continue code
}
I hope this helps!
i'm working on ASP.NET MVC project and every time i tried to run my view Register.cshtml i get this error :
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /User/Register
i'm trying to develop a Registration page with a view code :
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Register</h2>
<form action='#Url.Action("Register", "Controller")'>
<input type="hidden" name="FormType" value="A" />
<input type="hidden" name="FormType" value="B" />
<input type="text" name="Name" placeholder="enter your name" />
<input type="text" name="Password" placeholder="enter your name" />
<input type="radio" name="typeOfForm" class="radioBtn" value="A">Form A
<input type="radio" name="typeOfForm" class="radioBtn" value="B">Form B
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div style="display: none" id="formA" action="/actionA">
<input type="text" name="City" placeholder="City" /> <input type="submit" value="Register Me!" />
</div>
<div style="display: none" id="formB" action="/actionB">
<input type="text" name="Age" placeholder="Age" /><input type="submit" value="Register Me!" />
</div></form>
<script>
$('.radioBtn').click(function () {
var formType = $(this).val();
//alert(formType);
if (formType == "A") {
$('#FormA').show();
$('#FormB').hide();
} else {
$('#FormB').show();
$('#FormA').hide();
}
});</script>
with a UserController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BootstrapSite4.Controllers
{
public class UserController : Controller
{ [HttpGet]
[HttpPost]
// GET: User
public ActionResult Register(char FormType, string name, string password)
{
Seller S = new Seller();
DeliveryMan D = new DeliveryMan();
if (FormType=='A')
S.Name = name;
else
D.Name = name;
return View();}}}
i tried to change my RegisterRoutes but still getting the same error .. i think my error with the location only ! just a briefly description about the registration idea : i have tow types of users that will fill the registration form and depending on what they have chosen(in radio buttons) the rest of the form will appear in the same page to let them continue registration then add it to the right database .
You need to add an HttpGet Register method to the UserController as well:
[HttpGet]
public ActionResult Register()
{
return View();
}
Remember that you need 2 Register methods:
GET - Requests data from a resource - in this case requests to go to the Register view.
POST - Submitting data - in this case sends users info to the server, to register the user.
More reading on Http Get and Post
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 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.