【问题标题】:Add dynamic FileName to DotNetZip MVC Extension Method将动态文件名添加到 DotNetZip MVC 扩展方法
【发布时间】:2014-12-19 08:05:01
【问题描述】:

我正在使用 DotNetZip MVC 扩展方法示例添加多个文件(我从存储库中获取我的),但我似乎无法弄清楚如何将我自己的文件名传递给扩展方法并获得其他结果而不是“file.zip”,这是他们的示例硬编码默认值。下面是我的 CSHTML 代码、我的操作和我的扩展方法。你会在我的 Action 中看到我有一个想要使用的文件名。

我不好意思展示我的尝试,但你可以看到我想为我的文件名使用什么。有什么建议吗?

CSHTML(剃刀)

<a href="/Renders/Download/@renders.RenderId">Download</a>

控制器动作:

    public ActionResult Download(int id)
    {
        var allImages = _repo.GetImagesByRender(id);
        var list = new List<String>();

        var render = _repo.GetRenderById(id);
        var fileName = render.Select(r => r.Title);

        foreach (var img in allImages)
        {
            list.Add(Server.MapPath("~/ImageStore/" + img.Path));
        }

        return new ZipResult(list);
    }

扩展方法

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 clause guarantees that the Dispose() method is called implicitly!
        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);
        }
    }

} 

对于 Repo,它返回与 RenderId 关联的正确图像集合以及适当的 Render,以便我可以使用 Render Title 作为文件名,但是我将如何修改 ACtion 和扩展操作方法以使我的 zipFile 有正确的名称吗?

【问题讨论】:

    标签: c# asp.net-mvc razor streaming dotnetzip


    【解决方案1】:

    您可以向 ZipResult 类添加另一个构造函数:

    ...
    public ZipResult(IEnumerable<string> files, string fileName)
    {
        this._files = files;
        this._fileName = fileName;
    }
    ...
    

    然后在控制器中你可以使用它:

    ...
    return new ZipResult(list, "test.zip");
    

    【讨论】:

    • 我尝试了类似的方法。让我再看看我的代码。我想我知道我做错了什么......我想我忘记将我的文件名赋值值 ToString()....
    • 有时你需要有人指出显而易见的事情。我收到错误的原因是因为我试图将不是字符串的东西传递给方法。我真的很感谢你的帮助!当我看到你的“test.zip”时,我意识到它必须是一个字符串。
    • 我在新项目上试过了,效果很好。我只是从内容目录压缩静态文件。
    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2022-01-25
    • 1970-01-01
    • 2014-01-07
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多