使用 FileResult 在 Asp.Net MVC 中下载任何类型的文件? [英] Download file of any type in Asp.Net MVC using FileResult?

查看:26
本文介绍了使用 FileResult 在 Asp.Net MVC 中下载任何类型的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人建议我使用 FileResult 来允许用户从我的 Asp.Net MVC 应用程序下载文件.但是我能找到的唯一例子总是与图像文件有关(指定内容类型图像/jpeg).

I've had it suggested to me that I should use FileResult to allow users to download files from my Asp.Net MVC application. But the only examples of this I can find always has to do with image files (specifying content type image/jpeg).

但是如果我不知道文件类型怎么办?我希望用户能够从我网站的文件区下载几乎任何文件.

But what if I can't know the file type? I want users to be able to download pretty much any file from the filearea of my site.

我已经阅读了一种执行此操作的方法(请参阅上一篇文章 代码),实际上工作正常,除了一件事:另存为对话框中出现的文件名是从文件路径中用下划线连接起来的(folder_folder_file.ext).此外,似乎人们认为我应该返回 FileResult 而不是使用我找到的 BinaryContentResult 这个自定义类.

I had read one method of doing this (see a previous post for the code), that actually works fine, except for one thing: the name of the file that comes up in the Save As dialog is concatenated from the file path with underscores (folder_folder_file.ext). Also, it seems people think I should return a FileResult instead of using this custom class that I had found BinaryContentResult.

有谁知道在 MVC 中进行此类下载的正确"方式吗?

Anyone know the "correct" way of doing such a download in MVC?

我得到了答案(如下),但只是想如果其他人有兴趣,我应该发布完整的工作代码:

I got the answer (below), but just thought I should post the full working code if someone else is interested:

public ActionResult Download(string filePath, string fileName)
{
    string fullName = Path.Combine(GetBaseDir(), filePath, fileName);

    byte[] fileBytes = GetFile(fullName);
    return File(
        fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

byte[] GetFile(string s)
{
    System.IO.FileStream fs = System.IO.File.OpenRead(s);
    byte[] data = new byte[fs.Length];
    int br = fs.Read(data, 0, data.Length);
    if (br != fs.Length)
        throw new System.IO.IOException(s);
    return data;
}

推荐答案

您可以只指定通用的八位字节流 MIME 类型:

You can just specify the generic octet-stream MIME type:

public FileResult Download()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:foldermyfile.ext");
    string fileName = "myfile.ext";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

这篇关于使用 FileResult 在 Asp.Net MVC 中下载任何类型的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆