【发布时间】:2019-05-15 06:15:41
【问题描述】:
我已经完成了将文件保存到服务器文件夹的功能,**我现在正在尝试使用HTML download 从服务器取回文件,但还没有找到获取正确文件路径的方法.
在将文件存储在服务器的文件夹中后,使用实体框架将文件路径保存在数据库中,我使用filePath = /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png 从数据库中检索了file。但是这个 filePath 不能正常工作。
<a href="@file.Path" download="@file.name">Click here to download</a>
//file.Path = /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
我收到一个错误:Failed - No file
看看在 Controller 的 SaveFile 代码中创建 FilePath path:
private void SaveFile(HttpPostedFileBase file)
{
string serverPath = "\\VisitReportAttachments";
if (file!= null)
{
if (!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
var fileName = Guid.NewGuid()+ Path.GetExtension(file.FileName);
var path = Path.Combine("\\", new DirectoryInfo(serverPath).Name, fileName);
path = relativePath.Replace(@"\", "/"); //this path is stored to DB
....
//As I mentioned: save file to Server is done. I simply post the code that create the filepath in SQL DB while file is storing to Server*
}
}
FilePath 存储在 DB 中,例如:/VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
需要帮助!
【问题讨论】:
-
文件保存后需要返回。你是在使用 entityframework 将文件保存在数据库中吗?
-
实体框架将内容保存到数据库,而不是文件夹。您是否将实际文件保存到文件夹以及将路径字符串写入数据库?是什么阻止您从数据库中获取文件路径?您是否将其与任何类型的 ID 相关联以便您可以检索它?我注意到在您上面的代码中,所有重要的代码都丢失了,只有一个注释“TODO”。你真的为此写过一些代码吗?如果有,请出示,谢谢
-
好的,我使用Entity将filePath保存到SQL server,实际上文件存储在一个文件夹中。当然,我有一个 ID 可以检索它,这就是为什么我可以从 DB 获取 filePath: /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png。但问题是,使用 不正确的 filePath 不知道如何获得正确的 filePath 以使用下载功能作为链接。 @ADyson
-
@vyclarks 我在下面添加了我的答案。
-
那么,该文件夹是否在映射到 IIS 中的虚拟目录的目录中?如果没有,那么你需要这样做。要么,要么将
<a href指向一个 asp.net 方法,该方法接受图像 ID 并从文件中检索数据,并将其与必要的标题和 mime 类型一起呈现以供下载
标签: html asp.net-mvc