【发布时间】:2021-08-30 13:04:16
【问题描述】:
我正在尝试下载文件列表(用户可以选择多个)。我下面的当前代码在 localhost 中运行良好(编写并打开下载文件夹)。但是,当我上传到 IIS 时,它会给出一个错误,提示找不到系统配置。 请看下面:
if (SelectDownloadFiles.Count > 0)
{
//Downloads folder (User profile)
string DownloadFolder = Environment.ExpandEnvironmentVariables("%userprofile%/downloads/");
//This is a little hack to get the literal path for the Downloads folder without too much of back-and-forth and ellaboration
string FolderForward = DownloadFolder.Replace(@"/", @"\");
string Folder = FolderForward.Replace(@"\\", @"\");
foreach (var items in SelectDownloadFiles)
{
//Get Date
var GetDate = items.Substring(0, 6);
//Add 2 days to be consistent to what is displayed to the user (when files were generated)
var FileDate = DateTime.ParseExact(GetDate, "yyMMdd", CultureInfo.InvariantCulture).AddDays(2);
//Get Files
string Pathname = @"D:\";
string FullPathName = Path.Combine(Pathname, items);
byte[] FileBytes = System.IO.File.ReadAllBytes(FullPathName);
MemoryStream Ms = new MemoryStream(FileBytes);
//Rename the file to become user friendly
string DownloadPath = Path.Combine(DownloadFolder, "My Files " + FileDate.ToString("MM-dd-yyyy") + ".zip");
//Write file(s) to folder
FileStream File = new FileStream(DownloadPath, FileMode.Create, FileAccess.Write);
Ms.WriteTo(File);
File.Close();
Ms.Close();
}
//Open Downloads Folder with files
Process.Start("explorer.exe", Folder);
navigationManager.NavigateTo("/default", true);
//DisplayMessage.Show("File(s) successfully downloaded. Please check your “Downloads” folder to access your file(s).", "OK", "check");
}
else
{
Toaster.Add("Please select at least one file to download.", MatToastType.Warning);
}
我也尝试过使用下面的解决方案,但无济于事:
private readonly IWebHostEnvironment _webHostEnvironment;
public YourController (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
例如,如果我使用“文件夹选项路径”并选择“我的文档”,文件将下载到 IIS 内文件的根路径。 我还需要做些什么才能使其正常工作吗? 提前致谢!
【问题讨论】:
-
要让您的 Web 应用程序在服务器本地创建文件,您必须注意权限。一种方法是创建一个“临时”目录(不在 wwwroot 中)并为 IIS_IURS 用户(或在您的应用程序池中定义的其他用户)添加对该文件夹的读写权限。然后更改您的代码以在此目录中上传文件。
-
@GuyatMercator,写入用户的下载文件夹怎么样?这是一个选择吗?
-
问题是这段代码根本没有“下载”任何东西。它只是将文件系统写入它正在执行的机器上。当您在本地测试并且客户端和服务器恰好是同一设备时,这很好。正如您所发现的,当您将服务器移动到单独的机器上时,它就会出现问题。在普通的 Web 应用程序中,您实际上需要做的是准备一个包含文件数据和适当的 http 标头的 http 响应,以便浏览器将其视为下载而不是页面。在 blazor 中,我承认我不太确定最好的方法,但肯定不是你目前的方法。
-
附言。 stackoverflow.com/questions/52683706/… 可能是你需要的
标签: c# iis blazor server-side