File Upload Control Session Does Not Remove After Remove File From List
I had frustrated for a few week for this issue, How can I do session for this Multiple File Upload if (Session['FileUpload1'] == null && FileUploadQ2.HasFile) {
Solution 1:
As @VDWWD pointed out, you should not store files in the Session object - store them on disk instead. Below you can find fast implementation of that feature.
publicinterfaceIFileStorage
{
Task UploadFile(string fileName, Stream fileContent);
voidTryRemoveFile(string fileName, outbool fileRemoved);
voidGetFile(string fileName);
}
publicclassFileSystemStorage : IFileStorage
{
privatereadonly PhysicalFileProvider _fileProvider;
privatereadonly ILogger<FileSystemStorage>_logger;
publicFileSystemStorage(IFileProvider fileProvider, ILogger<FileSystemStorage> logger)
{
_fileProvider = (PhysicalFileProvider)fileProvider;
_logger = logger;
}
publicvoidGetFile(string fileName)
{
thrownew NotImplementedException();
}
publicvoidTryRemoveFile(string fileName, outbool fileRemoved)
{
try
{
RemoveFile(fileName);
fileRemoved = true;
}
catch(Exception ex)
{
_logger.LogError($"Couldnt remove file {fileName}: {ex.ToString()}" );
fileRemoved = false;
}
}
publicasync Task UploadFile(string fileName, Stream fileContent)
{
var filePath = Path.Combine(_fileProvider.Root, fileName);
if (_fileProvider.GetFileInfo(filePath).Exists)
thrownew ArgumentException("Given file already exists!");
_logger.LogInformation($"Saving file to: {filePath}..");
using (Stream file = File.Create(filePath))
{
await fileContent.CopyToAsync(file);
file.Flush();
}
_logger.LogInformation($"File: {filePath} saved successfully.");
}
}
In Startup.cs, ConfigureServices method add below lines to inject FileSystemStorage:
IFileProviderphysicalProvider=newPhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "AppData"));
services.AddSingleton<IFileProvider>(physicalProvider);
services.AddTransient<IFileStorage, FileSystemStorage>();
Then in your controller constructor obtain the FileSystemStorage instance.
Post a Comment for "File Upload Control Session Does Not Remove After Remove File From List"