我有可以使用控制器访问的网络驱动器。例如“ \ mydrive \ filestorage”。我希望用户能够下载存储在此服务器上的文件。这意味着我无法使用URL,因为这些文件不在Web服务器根目录之外。我也无法为此驱动器设置Web服务器,除了使用控制器读取文件并以这种方式下载文件外,我没有其他方法可以访问此数据。
我已经找到一些教程来针对服务器上的文件执行此操作,但是当使用远程文件时,我无法使其正常工作。我想要一个下载链接,单击它,然后下载文件。这是我的代码
public ActionResult DownloadFile(string id)
{
UploadedDocument document = new UploadedDocument(Int32.Parse(id));
string filecontents = System.IO.File.ReadAllText(document.FilePath);
string filetype = Helpers.GetMimeType(document.FilePath);
return File(filecontents, filetype);
}
我得到以下异常
System.IO.DirectoryNotFoundException:找不到路径'C:\ inetpub \ wwwroot ...的一部分...
filepath变量将是网络驱动器的路径。
\\Netdrive\Uploads\somefile.txt
文件内容和文件类型的2个变量已正确填充。返回文件时将引发异常。当我在调试模式下运行代码时,将按以下方式填充2个变量。
filecontents = "test\r\n"
filetype = "text\plain"
File(string, string)
需要一个文件名和一个mime类型,但是您正在将文件内容作为字符串传递。
通过这种方式直接从网络驱动器提供文件:
public ActionResult DownloadFile(string id)
{
UploadedDocument document = new UploadedDocument(Int32.Parse(id));
string filetype = Helpers.GetMimeType(document.FilePath);
return File(document.FilePath, filetype);
}
要强制下载文件(并绕过默认的浏览器设置文件处理,例如浏览器中显示的PDF),请添加文件名作为File方法的第三个参数:
return File(document.FilePath, filetype, "myFileName.pdf");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句