I am uploading multiple files asynchronously using ASP.NET Core. As soon as the user clicks browse and selects multiple files the request is sent to the server. They are being processed simultaneously so debugging seems very strange.
I would like to allow the user to upload multiple files at once, but process them in order in the following way:
File1: Save to filesystem and store info about file in database.
File2: When everything from File1 is completely finished, Save to filesystem and store info about the file in database.
File3: When everything from File2 is completely finished, Save to filesystem and store info about the file in database.
The problem that I am facing is that File2 database info relies on data from File1, File3 database info relies on data from File2... I want to make a call to the database to get the previous file to do this but I can't because it never exists yet due to the way everything is processing.
There is a setting for the uploader control I am using called: SequentialUpload. This setting seems like it should help with exactly what I want based on the description, but in the debugger it still looks strange and I am unable to process in order.
When you enable the sequentialUpload property, the selected files will process sequentially (one after the other) to the server. If the file uploaded successfully or failed, the next file will upload automatically in this sequential upload.
Below is what my server-side function looks like, excluding the saving info to the database since that is business logic:
// Upload method for chunk-upload and normal upload
public IActionResult Save(IList<IFormFile> UploadFiles)
{
long size = 0;
// for normal upload
try
{
foreach (var file in UploadFiles)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
if (!System.IO.File.Exists(filename))
{
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
// LOGIC TO RETRIEVE INFO ABOUT PREVIOUSLY STORED FILE FROM DB HERE
// LOGIC TO STORE INFO ABOUT CURRENT FILE TO DB HERE
}
}
}
catch (Exception e)
{
Response.Clear();
Response.StatusCode = 204;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
return Content("");
}
It would be perfect if File1 is processed then I end up in the success function on the client and then File2 is kicked off and so on... Instead I always end up in the success function after all processing is done.