【问题标题】:Html correct filePath for downloading file from Server用于从服务器下载文件的 Html 正确文件路径
【发布时间】: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 中的虚拟目录的目录中?如果没有,那么你需要这样做。要么,要么将 &lt;a href 指向一个 asp.net 方法,该方法接受图像 ID 并从文件中检索数据,并将其与必要的标题和 mime 类型一起呈现以供下载

标签: html asp.net-mvc


【解决方案1】:

通过使用Server.MapPath 将文件路径映射到正确的路径找到解决方案。

我没有在 HTML 视图中使用可下载的链接,而是在控制器中创建了下载功能:

[HttpPost]
        [Authorize]
        public ActionResult DownloadAttachment()
        {
            return Json(true);
        }

        [HttpGet]
        public ActionResult Download(Guid? attachmentId)
        {
            var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
            try
            {
                var serverPath = Server.MapPath(visitAttachment.Path);
                byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);

            }
            catch
            {
                return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
            }

        }

在视图中调用这个方法:

<a href="" onclick="Download('@file.Id');">@file.AttachmentName</a>

<script>
    function Download(attachmentId) {
            var url = '/Visits/DownloadAttachment';
            $.post(url,
                {
                    //                  FilePath: filePath
                },
                function (data) {
                    var response = JSON.parse(data);
                    window.location = '/Visits/Download?attachmentId=' + attachmentId;
                },
                "json");
        }
    </script>

现在完美运行。

【讨论】:

  • 很高兴您修复了它...但是在这里发出 AJAX 请求的目的是什么?该请求没有返回任何有用的信息,并且无论如何您都不会对响应做任何事情。我希望&lt;a href="/Visits/Download?attachmentId=@file.Id"&gt;@file.AttachmentName&lt;/a&gt; 会直接完成这项工作。这样就可以减少对服务器的 HTTP 请求,并且无需维护额外的 AJAX 代码
  • 使用 @file.AttachmentName 将网站导航到一个视图名称下载,我要下载它在当前页面
  • window.location 也会将网站导航到该 URL。这完全等同于单击链接。见stackoverflow.com/questions/1667416/…。并且它不能将您带到名为 Download 的视图,因为 a) 您没有下载,并且 b) 该 URL 链接到的操作方法不返回视图。你真的尝试过直接使用 a href 吗?与使用 JavaScript 相比,你真的得到了不同的结果吗?据我所知,您应该不会注意到任何差异。
【解决方案2】:

您的private string SaveFile(HttpPostedFileBase file) 方法应该返回一个NewFile 模型对象,该对象反映了您数据库中的实体。 private NewFile SaveFile(HttpPostedFileBase file)

public class NewFile
{
   public int NewFileId { get; set; } 
   public string FileName { get; set; }
   public string FilePath { get; set; }
}

保存文件时,您需要执行类似于以下代码的操作:

using (var db = new YourDbContext())
{
   var newFile = new NewFile { FileName = fileName, FilePath = path };

   var savedFile = db.Add(newFile);

   db.SaveChanges();

   return savedFile;   // here is the object you can return to the view and access 
                       // its properties
}

【讨论】:

  • 谢谢,但我已经从 DB 获得了 filePath。但在此语法中使用的文件路径不正确:@file.name。这就是我所要求的。文件路径是 /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
  • 当然,我做到了,然后得到了@model.Path = /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
  • 所以当您点击链接时,您正在尝试下载 png 文件?它没有找到它。VisitReportAttachments 是您解决方案中的文件夹吗?
【解决方案3】:
    private string SaveFile(HttpPostedFileBase file)
    {
        if (file == null)
            return string.Empty;

        string saveFolder = "VisitReportAttachments";

        string fileName = fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        string serverFolderPath = AppDomain.CurrentDomain.BaseDirectory + "/" + saveFolder;
        string savePath = serverFolderPath + "/" + fileName;


        if (!Directory.Exists(serverFolderPath))
            Directory.CreateDirectory(serverFolderPath);

        file.SaveAs(savePath);

        return Url.Content($"~/{saveFolder}/{fileName}");
    }

【讨论】:

  • 谢谢,但我已经从 DB 获得了 filePath。但在此语法中使用的文件路径不正确:@file.name。这就是我所要求的。文件路径是 /VisitReportAttachments/1ea2b64e-545d-4c50-ae7d-eefa7178d310.png
【解决方案4】:

您没有保存文件夹中的文件。 在代码中添加以下行

file.SaveAs(serverPath + file.FileName);

所以你的 C# 代码会是这样的

private string 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);

         file.SaveAs(serverPath + file.FileName);

         path = relativePath.Replace(@"\", "/");

         return path;
        }
         return string.Empty;
}

【讨论】:

  • 请仔细阅读我的问题。我使用实体框架将文件保存到文件夹,它很长,所以我不会在我的问题中发布它。我的问题是如何再次获得正确的文件路径来下载它
  • 您是否已将文件保存到 /VisitReportAttachments ?
猜你喜欢
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
相关资源
最近更新 更多