Reputation: 7219
I am posting one or more files from my Vue.js frontend. It's being done as such:
<form enctype="multipart/form-data" novalidate v-if="isInitial || isSaving">
<div class="dropbox">
<input type="file" multiple :name="uploadFieldName" :disabled="isSaving" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length" accept=".json" class="input-file">
<p v-if="isInitial">
Drag files here to begin <br> or click to browse
</p>
<p v-if="isSaving">
Uploading {{ fileCount }} files...
</p>
</div>
</form>
I then post it via this method:
function upload(formData) {
const url = `${BASE_URL}/api/upload`;
return axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
Which seems to do the job.
Following Microsoft's own guide, I have created the following endpoint:
namespace WebApplication6.Controllers
{
public class UploadController : Controller
{
[HttpPost]
[Route("/api/upload")]
public async Task<IActionResult> UploadFiles(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files <-- What does this entail? How do I access the stream?
return Ok(new { count = files.Count, size, filePath });
}
}
}
I am somewhat new to C# coming from Java: What does the Microsoft docs found here mean when they say "process uploaded files"?
How do I access them from the memory stream? Why is the comment outside the for loop - if I had to do stuff with the files, it should be on it - or not?
Upvotes: 1
Views: 7088
Reputation: 77304
Wow that Microsoft example is horrible.
Assuming you have a single IFormFile
named formFile
(I trust you be able to write that loop yourself), the simplest way to get to the barebones is:
using (var memoryStream = new MemoryStream())
{
await formFile.CopyToAsync(memoryStream);
byte[] bytes = memoryStream.ToArray();
// do what you want with the bytes
}
You just copied the bytes twice, in the original formfile, in the stream and then into the byte array, so when you have more experience in .NET you may want to optimize it a bit. Maybe proceed your processing with the memory stream directly instead of the byte array.
Upvotes: 3
Reputation: 2072
It appears the Microsoft docs may be a bit misleading.
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
// here you have access to each individual file
}
}
}
Inside the using
statement, you can manipulate the stream
object, i.e. save it out to its unique file path, process data within the file (if a .csv
), etc. The question is a bit broad but the Microsoft article may be a bit misleading to you.
Upvotes: 1