【问题标题】:How to make function make download file from path on asp.net core 2.2?如何使功能从 asp.net core 2.2 上的路径下载文件?
【发布时间】:2021-03-01 06:30:59
【问题描述】:

我从事项目使用 .net core 2.2 visual studio 2017 Web API

我需要制作函数下载文件

给出文件的函数路径将是下载和下载文件并返回Void。

我需要在 .net core 2.2 上制作函数下载文件,以便在动作控制器中重用它。

public void DownloadOutPut(string path)
{
    try
    {


        if (path != "")
        {


            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {

                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename = " + file.Name + "");
                Response.TransmitFile(path);


            }

            Response.End();
        }
    }
    catch (Exception ex)
    {

        throw;
    }
}

以上是在 asp.net web 表单上完成的,我需要在 .net core 2.2 上做类似的功能

那么请问该怎么做呢?

【问题讨论】:

  • path 是什么?文件的 URL?服务器或客户端文件的路径?
  • 这能回答你的问题吗? How to download a file in ASP.NET Core
  • 是的,解决了我的问题
  • 只有一个问题,如果我需要将下载文件下载到下载文件夹并在浏览器上显示为文件,这将与 Web api 或客户端角度或 jquery 有关

标签: c# asp.net-mvc ado.net asp.net-core-webapi asp.net-core-2.2


【解决方案1】:

我假设您正在接收映射路径,并且文件已放置在您的服务器上。

public FileStreamResult DownloadFile(string path)
{
    var filename = System.IO.Path.GetFileName(path);
    var mimeType = "application/octet-stream";
    var stream = System.IO.File.OpenRead(path);

    return new FileStreamResult(stream, mimeType) { FileDownloadName = filename };
}

对于 mimetypes,我发现这个 SO 回答很有帮助。

【讨论】:

    猜你喜欢
    • 2022-06-26
    • 2020-11-17
    • 2021-02-26
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2019-11-26
    相关资源
    最近更新 更多