从列表中删除文件后,文件上传控制会话不会删除 [英] 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)
{
Session["FileUpload1"] = FileUploadQ2;
foreach (HttpPostedFile file in FileUploadQ2.PostedFiles)
{
listofuploadedfiles.Text += String.Format("<p><font color='black'>" + file.FileName + "</font><a class='close'><font color='red'>x</font><a>" + "</p>");
}
}
else if (Session["FileUpload1"] != null && (!FileUploadQ2.HasFile))
{
FileUploadQ2 = (FileUpload)Session["FileUpload1"];
}
else if(FileUploadQ2.HasFile)
{
Session["FileUpload1"] = FileUploadQ2;
}
推荐答案
正如@VDWWD所指出的那样,您不应将文件存储在Session对象中,而应将其存储在磁盘上.您可以在下面找到该功能的快速实现.
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.
public interface IFileStorage
{
Task UploadFile(string fileName, Stream fileContent);
void TryRemoveFile(string fileName, out bool fileRemoved);
void GetFile(string fileName);
}
public class FileSystemStorage : IFileStorage
{
private readonly PhysicalFileProvider _fileProvider;
private readonly ILogger<FileSystemStorage>_logger;
public FileSystemStorage(IFileProvider fileProvider, ILogger<FileSystemStorage> logger)
{
_fileProvider = (PhysicalFileProvider)fileProvider;
_logger = logger;
}
public void GetFile(string fileName)
{
throw new NotImplementedException();
}
public void TryRemoveFile(string fileName, out bool fileRemoved)
{
try
{
RemoveFile(fileName);
fileRemoved = true;
}
catch(Exception ex)
{
_logger.LogError($"Couldnt remove file {fileName}: {ex.ToString()}" );
fileRemoved = false;
}
}
public async Task UploadFile(string fileName, Stream fileContent)
{
var filePath = Path.Combine(_fileProvider.Root, fileName);
if (_fileProvider.GetFileInfo(filePath).Exists)
throw new 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.");
}
}
在Startup.cs中,ConfigureServices方法添加以下行以注入FileSystemStorage:
In Startup.cs, ConfigureServices method add below lines to inject FileSystemStorage:
IFileProvider physicalProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "AppData"));
services.AddSingleton<IFileProvider>(physicalProvider);
services.AddTransient<IFileStorage, FileSystemStorage>();
然后在控制器构造函数中获取FileSystemStorage实例.
Then in your controller constructor obtain the FileSystemStorage instance.
这篇关于从列表中删除文件后,文件上传控制会话不会删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文