思路:HTML的input标签支持文件夹输入,输入的结果是“文件夹路径名(从所选的文件夹开始)/文件名”格式,传入asp.net的controller的格式是IFormFileCollection,在action里遍历一下即可
1.前端代码
<!--上传文件夹-->
<form id="folderUploadForm" action="/home/UploadFolder" method="post" enctype="multipart/form-data"> <!--其中action参数对应controller中的action-->
<input id="folderInput" type="file" name="formFiles" webkitdirectory directory multiple /> <!--name要与controller中对应的上传方法的参数名相同;定义input可以接收文件夹-->
<input type="submit" value="上传" id="uploadBtn1" />
</form>
2.后端controller中的代码
[HttpPost]
public async Task<dynamic> UploadFolder(IFormFileCollection formFiles) //通过form上传文件夹,不带进度条
{
string folderName = "";
for (int i = 0; i < formFiles.Count; i++) //遍历文件
{
folderName = @$"C:\web2\wwwroot\{formFiles[i].FileName.Replace(formFiles[i].FileName.Split("/")[formFiles[i].FileName.Split("/").Length - 1], "")}"; //获得每个文件在服务器中拟上传的文件夹路径。其中“C:\web2\wwwroot\”是在服务器中保存文件的位置
if (!Directory.Exists(folderName)) //如果文件夹路径不存在就新建一下(主要应用于子文件夹)
Directory.CreateDirectory(folderName);
var filePath = Path.Combine(@$"C:\web2\wwwroot\{formFiles[i].FileName}"); //其中“C:\web2\wwwroot\”是在服务器中保存文件的位置
HttpContext.Session.SetString("UploadPath", filePath); //使用session前,需在Program.cs中添加builder.Services.AddSession()、app.UseSession()
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await formFiles[i].CopyToAsync(stream);
}
}
return Content("已上传文件夹");
}