如何在ASP.NET Core中下载文件

时间:2017-08-17 06:18:49

标签: asp.net-core

在MVC中,我们使用以下代码下载文件。在ASP.NET核心中,如何实现这一目标?

HttpResponse response = HttpContext.Current.Response;                 
System.Net.WebClient net = new System.Net.WebClient();
string link = path;
response.ClearHeaders();
response.Clear();
response.Expires = 0;
response.Buffer = true;
response.AddHeader("Content-Disposition", "Attachment;FileName=a");
response.ContentType = "APPLICATION/octet-stream";
response.BinaryWrite(net.DownloadData(link));
response.End();

9 个答案:

答案 0 :(得分:14)

您的控制器应返回IActionResult,并使用File方法,例如:

[HttpGet("download")]
public IActionResult GetBlobDownload([FromQuery] string link)
{
    var net = new System.Net.WebClient();
    var data = net.DownloadData(link);
    var content = new System.IO.MemoryStream(data);
    var contentType = "APPLICATION/octet-stream";
    var fileName = "something.bin";
    return File(content, contentType, fileName);
}

答案 1 :(得分:4)

您可以尝试以下代码下载该文件。它应该返回FileResult

public ActionResult DownloadDocument()
{
string filePath = "your file path";
string fileName = ""your file name;

byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

return File(fileBytes, "application/force-download", fileName);

}

答案 2 :(得分:2)

Asp.net Core 2.1+示例(最佳做法)

Startup.cs:

private readonly IHostingEnvironment _env;

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
    Configuration = configuration;
    _env = env;
}

services.AddSingleton(_env.ContentRootFileProvider); //Inject IFileProvider

SomeService.cs:

private readonly IFileProvider _fileProvider;

public SomeService(IFileProvider fileProvider)
{
    _fileProvider = fileProvider;
}

public FileStreamResult GetFileAsStream()
{
    var stream = _fileProvider
        .GetFileInfo("RELATIVE PATH TO FILE FROM APP ROOT")
        .CreateReadStream();

    return new FileStreamResult(stream, "CONTENT-TYPE")
}

控制器将返回IActionResult

[HttpGet]
public IActionResult Get()
{
    return _someService.GetFileAsStream() ?? (IActionResult)NotFound();
}

答案 3 :(得分:2)

Action方法需要使用流,字节[]或文件的虚拟路径返回FileResult。您还需要知道要下载的文件的内容类型。这是一个示例(快速/脏)实用程序方法。样本视频链接 How to download files using asp.net core

[Route("api/[controller]")]
public class DownloadController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Download()
    {
        var path = @"C:\Vetrivel\winforms.png";
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            ...
        };
    }
}

答案 4 :(得分:0)

创建一个服务,例如FileService。

public class FileService
{
    private readonly IHostingEnvironment _hostingEnvironment;
    constructor(IHostingEnvironment hostingEnvironment)
    {
        this._hostingEnvironment = hostingEnvironment;
    }
}

向文件的FileService MimeType添加方法

private string GetMimeType(string fileName)
{
    // Make Sure Microsoft.AspNetCore.StaticFiles Nuget Package is installed
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    if (!provider.TryGetContentType(fileName, out contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;
}

现在添加一种下载文件的方法,

public FileContentResult GetFile(string filename) 
{
    var filepath = Path.Combine($"{this._environment.WebRootPath}\\path-to-required-folder\\{filename}");

    var mimeType = this.GetMimeType(filename); 

    byte[] fileBytes;

    if (File.Exists(filepath))
    {
        fileBytes = File.ReadAllBytes(filepath); 
    } 
    else
    {
        // Code to handle if file is not present
    }

    return new FileContentResult(fileBytes, mimeType)
    {
        FileDownloadName = filename
    };
}

现在添加控制器方法并在FileService中调用GetFile方法,

 public IActionResult DownloadFile(string filename) 
 {
    // call GetFile Method in service and return       
 }

答案 5 :(得分:0)

一个相对简单的方法是使用内置的PhysicalFile结果,该结果可用于所有控制器:MS Docs: PhysicalFile

一个简单的例子:

public IActionResult DownloadFile(string filePath)
{
     return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
}

由于安全方面的考虑,现在当然不应该公开这种API。

我通常将实际文件路径屏蔽在一个友好标识符之后,然后使用该标识符查找真实文件路径(如果传入无效ID,则返回404),即:

[HttpGet("download-file/{fileId}")]
public IActionResult DownloadFile(int fileId)
{
    var filePath = GetFilePathFromId(fileId);
    if (filePath == null) return NotFound();

    return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
}

对于好奇的人,MimeTypes帮助器是来自MimeKit的人们的一个很棒的小工具包。

答案 6 :(得分:0)

我将示例上传到了公开的Github存储库:https://github.com/tsafadi/FileDownloadSample

无论哪种方式,控制器的外观都应该如此:

[HttpGet]
public IActionResult DownloadFile()
{
    // Since this is just and example, I am using a local file located inside wwwroot
    // Afterwards file is converted into a stream
    var path = Path.Combine(_hostingEnvironment.WebRootPath, "Sample.xlsx");
    var fs = new FileStream(path, FileMode.Open);

    // Return the file. A byte array can also be used instead of a stream
    return File(fs, "application/ocet-stream", "Sample.xlsx");
}

在视图内部:

$("button").click(function () {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "Download/DownloadFile", true);
    xhr.responseType = "blob";
    xhr.onload = function (e) {
        if (this.status == 200) {
            var blob = this.response;

            /* Get filename from Content-Disposition header */
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }

            // This does the trick
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = filename;
            a.dispatchEvent(new MouseEvent('click'));
        }
    }
    xhr.send();
});

答案 7 :(得分:0)

我的方法很短,我认为它适合大多数人的需求。

  [HttpPost]
  public ActionResult Download(string filePath, string fileName)
  {
      var fileBytes = System.IO.File.ReadAllBytes(filePath);
      new FileExtensionContentTypeProvider().TryGetContentType(Path.GetFileName(filePath), out var contentType);
      return File(fileBytes, contentType ?? "application/octet-stream", fileName);
  }

答案 8 :(得分:0)

    [HttpGet]
    public async Task<FileStreamResult> Download(string url, string name, string contentType)
    {
        var stream = await new HttpClient().GetStreamAsync(url);

        return new FileStreamResult(stream, contentType)
        {
            FileDownloadName = name,
        };
    }
相关问题