In the new ASP.NET Core development model , you use Interface
IFormFile which is responsible for working with% type% input
.
The problem that is happening is that the value should be a list and not 1 element, because your form setting in
file
is with
input
, example :
multiple
.
Basic example:
Html
<form role="form" asp-action="Upload" enctype="multipart/form-data">
<input type="file" name="id" id="id" multiple />
<input type="submit" value="Upload" />
</form>
Controller
public async Task<IActionResult> Upload(List<IFormFile> id)
Being a very important factor, the name of List<IFormFile>
is the same name that is placed in the folder that will receive the files, for example, you put input
in the name of id
it must follow the same name for the input
.
How will you get the values being what your setting was in a list?
I've set a minimal example to illustrate this, where controller
can send multiple files to input
:
Xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<cliente>
<id>1</id>
<nome>stackoverflow</nome>
</cliente>
</root>
Html
<form role="form" asp-action="Upload" enctype="multipart/form-data">
<input type="file" name="id" id="id" multiple />
<input type="submit" value="Upload" />
</form>
Controller
[AcceptVerbs("POST", "GET")]
public async Task<IActionResult> Upload(List<IFormFile> id)
{
if (Request.Method.Equals("POST"))
{
foreach (var formFile in id)
{
if (formFile.Length > 0)
{
using (MemoryStream str = new MemoryStream())
{
formFile.CopyTo(str);
str.Position = 0;
var xml = (from x in XDocument.Load(str).
Descendants("cliente")
let _id = x.Element("id").Value
let _nm = x.Element("nome").Value
select new
{
Id = _id,
Nome = _nm
})
.FirstOrDefault();
}
}
}
}
return View();
}
In the example example I only sent one, but with the same layout as controller
you can send several, if you prefer.
Remember that if it's just 1 file at a time, just take the part of the collection as follows:
Xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<cliente>
<id>1</id>
<nome>stackoverflow</nome>
</cliente>
</root>
Html
<form role="form" asp-action="Upload" enctype="multipart/form-data">
<input type="file" name="id" id="id" />
<input type="submit" value="Upload" />
</form>
Controller
[AcceptVerbs("POST", "GET")]
public async Task<IActionResult> Upload(IFormFile id)
{
if (Request.Method.Equals("POST"))
{
if (id.Length > 0)
{
using (MemoryStream str = new MemoryStream())
{
await id.CopyToAsync(str);
str.Position = 0;
var xml = (from x in XDocument.Load(str).
Descendants("cliente")
let _id = x.Element("id").Value
let _nm = x.Element("nome").Value
select new
{
Id = _id,
Nome = _nm
})
.FirstOrDefault();
}
}
}
return View();
}
that is, in Xml
take the setting input
and in multiple
leave only the interface IFormFile
References