下载使用FileResult任何类型的Asp.Net MVC的文件? [英] Download file of any type in Asp.Net MVC using FileResult?
问题描述
我已经受够了建议,我认为我应该使用FileResult允许用户从我的Asp.Net MVC应用程序下载文件。但是这个我总能找到的唯一的例子有图像文件(指定内容类型image / jpeg)这个做。
但如果我不知道该文件类型?我希望用户能够从我的网站filearea多下载pretty的任何文件。
我曾经读过这样的一种方法(见 previous帖子为code),实际工作得很好,除了一件事:当对话框从文件路径连接在一起下划线(folder_folder_file.ext在保存出现的文件名)。此外,人们似乎认为我应该返回FileResult而不是使用,我发现这个BinaryContentResult自定义类的。
任何人都知道在MVC做这样的下载的正确的方法是什么?
编辑:
我得到了答案(下同),但只是觉得我应该张贴了完整的工作code,如果别人有兴趣:
公众的ActionResult下载(字符串文件路径,字符串文件名)
{
字符串全名= Path.Combine(GetBaseDir(),文件路径,文件名); 字节[] = fileBytes的GetFile(全名);
返回文件(
fileBytes,System.Net.Mime.MediaTypeNames.Application.Octet,文件名);
}字节[]的GetFile(字符串s)
{
System.IO.FileStream FS = System.IO.File.OpenRead(多个);
字节[]数据=新的字节[fs.Length]
INT BR = fs.Read(数据,0,data.Length);
如果(BR!= fs.Length)
抛出新System.IO.IOException(S);
返回的数据;
}
您只需指定通用八位字节流MIME类型:
公共FileResult下载()
{
字节[] = fileBytes System.IO.File.ReadAllBytes(@C:\\文件夹\\ myfile.ext);
字符串文件名=myfile.ext;
返回文件(fileBytes,System.Net.Mime.MediaTypeNames.Application.Octet,文件名);
}
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.
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.
Anyone know the "correct" way of doing such a download in MVC?
EDIT: 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;
}
You can just specify the generic octet-stream MIME type:
public FileResult Download()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext");
string fileName = "myfile.ext";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
这篇关于下载使用FileResult任何类型的Asp.Net MVC的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!