MVC ActionResult
可以返回多个文件吗?如果是这样,它可以返回多个类型的多个文件吗?
示例:
ActionResult
可以返回myXMLfile1.xml,myXMLfile2.xml和myfile3.xml吗?
ActionResult
可以返回myXMLfile4.xml和myTXTfile1.txt吗?
如何实现这一目标?
答案 0 :(得分:5)
您无法返回多个文件,但是,您可以压缩.zip
文件中的多个文件并返回此压缩文件,例如,在项目中创建自定义ActionResult,如下所示:
public class ZipResult : ActionResult
{
private IEnumerable<string> _files;
private string _fileName;
public string FileName
{
get
{
return _fileName ?? "file.zip";
}
set { _fileName = value; }
}
public ZipResult(params string[] files)
{
this._files = files;
}
public ZipResult(IEnumerable<string> files)
{
this._files = files;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile zf = new ZipFile())
{
zf.AddFiles(_files, false, "");
context.HttpContext
.Response.ContentType = "application/zip";
context.HttpContext
.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
zf.Save(context.HttpContext.Response.OutputStream);
}
}
}
并像这样使用它:
public ActionResult Download()
{
var zipResult = new ZipResult(
Server.MapPath("~/Files/file1.xml"),
Server.MapPath("~/Files/file2.xml"),
Server.MapPath("~/Files/file3.xml")
);
zipResult.FileName = "result.zip";
return zipResult;
}
在此处查看更多内容:http://www.campusmvp.net/blog/asp-net-mvc-return-of-zip-files-created-on-the-fly