从MVC下载文件

jimfromthegym-吉姆·麦金

当用户单击angular / script中的图标并将其发送到.NET中的MVC控制器时,我需要一种传递字符串列表的方法。此列表会执行所需的操作,然后应该在我的浏览器中下载文件。我了解到我无法通过AJAX执行此操作,并且/或者它变得非常混乱。

编辑:字符串列表是指我要检索的文件ID列表,然后将其压缩为一个文件,该文件将被下载。我不想将此压缩文件永久存储在任何地方。

我愿意接受想法!

        $http.post('document/downloadfiles', data).success(function ()         {/*success callback*/ });

    [HttpPost]
    public ActionResult DownloadFiles(List<string> fileUniqueIdentifiers)
    {
           var file =    _service.ArchiveAndDownloadDocuments(fileUniqueIdentifiers);

        file.Position = 0;

        return new FileStreamResult(file, "application/force-download");


    }
OBR_EXO

好吧,我猜是第三次幸运吗?(对不起,吉姆,我认为这将是我的最后一次实施-您必须自己完成剩下的工作,我想我现在已经为您提供了足够多的免费指针...如果您想要更多,可以与我联系我会要求您写的!:P)。

这个版本使用基于Cookie的交换,从javascript接受输入字符串(假设它们是文件名),将它们与令牌一起存储在实例类中作为键,然后在内存中组装ZipFile(无需写入磁盘),然后返回该zipfile作为内容结果。为了提高效率,您可以删除针对GUID列表的实际令牌检查,而仅针对文件列表中的密钥进行检查。显然,您可能不希望像我所做的那样在该javascript中对文件名进行硬编码,但是您可以自己解决这一问题。提示:创建一个具有标识符/文件路径对的数据库表,并在将请求发送到服务器后使用标识符查找各个文件路径...

查看部分(我将我的添加到index.cshtml中):

<script type="text/javascript">
    function sendStringandGetFiles() {

        var files = ['c:\\temp\\afile.txt', 'c:\\temp\\afile2.txt', 'c:\\temp\\afile3.txt'];

        $.ajax({
            type: "POST",
            url: "/Home/GetFile",
            contentType: 'application/json',
            data: JSON.stringify(files),
            success: function (result) {
                //alert("Yes This worked! - " + result);
                window.location = "/Home/GetFile";
            }
        });
    }
</script>

<h5>Just something to click</h5>
<button onclick="sendStringandGetFiles()">Send String and Get Files</button>

然后是控制器部分(我使用了HomeController.cs)

    [AcceptVerbs(HttpVerbs.Post)]
    public string GetFile(string[] strings)
    {
        Guid token = Guid.NewGuid();

        InMemoryInstances instance = InMemoryInstances.Instance;

        instance.addToken(token.ToString());

        instance.addFiles(token.ToString(), strings);

        HttpCookie cookie = new HttpCookie("CookieToken");

        cookie.Value = token.ToString();

        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

        return token.ToString();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult GetFile()
    {
        InMemoryInstances instance = InMemoryInstances.Instance;

        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("CookieToken"))
        {
            HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["CookieToken"];

            if (instance.checkToken(cookie.Value)) 
            {                                
                cookie.Expires = DateTime.Now.AddDays(-1);

                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

                MemoryStream ms = new MemoryStream();

                string[] filenames = instance.getFiles(cookie.Value);

                using (ZipArchive zs = new ZipArchive(ms,ZipArchiveMode.Create, true))
                {
                    for (int i=0;i < filenames.Length; i++)
                        zs.CreateEntryFromFile(filenames[i], Path.GetFileName(filenames[i]));                        
                }

                FileContentResult resultContent = new FileContentResult(ms.ToArray(),"application/zip");

                instance.removeFiles(cookie.Value);

                resultContent.FileDownloadName = "ARandomlyGeneratedFileNameHere.zip";

                return resultContent;
            } else 
            {
                return View("Index");
            }
        }            
        else
        {
            return View("Index");
        }

    }

InMemoryInstances类:

public class InMemoryInstances
{
    private static volatile InMemoryInstances instance;
    private static object syncRoot = new Object();

    private List<Guid> activeTokens;
    private NameValueCollection filesByKeyCollection;

    private InMemoryInstances() 
    {
        activeTokens = new List<Guid>();
        filesByKeyCollection = new NameValueCollection();
    }

    public static InMemoryInstances Instance
    {
        get 
        {
            if (instance == null) 
            {
                lock (syncRoot)                  
                {
                    if (instance == null) 
                        instance = new InMemoryInstances();
                }
            }

            return instance;
        }
    }

    public bool checkToken(string token)
    {
        return activeTokens.Contains(new Guid(token));
    }

    public string[] getFiles(string token)
    {
        return filesByKeyCollection.GetValues(token);
    }

    public bool addFiles(string token, string[] files)
    {
        for (int i = 0; i < files.Length; i++)
            filesByKeyCollection.Add(token, files[i]);

        return true;
    }

    public bool addToken(string token)
    {
        activeTokens.Add(new Guid(token));
        return true;
    }

    public bool removeFiles(string token)
    {
        filesByKeyCollection.Remove(token);
        return true;
    }

    public bool removeToken(string token)
    {
        return activeTokens.Remove(new Guid(token));
    }
}

希望这可以帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章