用ajax生成文件并允许用户下载它? [英] Generating file with ajax and allow user to download it?

查看:158
本文介绍了用ajax生成文件并允许用户下载它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的问题:允许用户下载文件-ASP .NET ,但就我而言,我正在使用ajax生成xlsx文件,并且在使用ajax的称为aspx页面上使用:

I have very similar problem as this: Allowing users to download files - ASP.NET , but in my case I am generating xlsx file with ajax, and on ajax-called aspx page I am using:

Response.Clear();
Response.ContentType = "application/octet-stream";
string filename = User.Identity.Name + "_Report.xlsx";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.WriteFile(AppDomain.CurrentDomain.BaseDirectory + "Reports\\" + filename);
Response.End();

生成此文件时,控制权返回到ajax调用页面,从那里我将不会基于此ajax响应显示保存文件对话框,并允许用户下载此生成的文件.由于IE中的弹出窗口阻止程序,我不想使用称为page的ajax将文件保存在磁盘上,然后将ajax调用页面重定向到该文件.我正在使用jquery进行ajax调用:

When this file is generated, control is returned to ajax calling page and from there I wan't to show save file dialog based on this ajax response and allow user to download this generated file. I don't want to save file on disk with ajax called page and then redirect ajax calling page to that file, because of popup blocker in IE. I am using jquery for ajax calls:

$.ajax({  
    type:"POST", 
    url: "AjaxReport.aspx",               
    data:dataString,
    success: function(data) {
        //don't want to use this  
        // $('#RedirectIFrame').attr('src','Reports/Report.xlsx?cache='+Math.random());
        //want to use data variable containing ajax response (bytes of Report file) showing
        //save dialog to download this file from browser
    }              
});   

该怎么做?

推荐答案

当前,JavaScript无法访问用户的文件系统,这意味着您无法提示用户保存来自网络流的文件.

Currently JavaScript can't access to the user's file system, meaning you can't prompt users to save a file coming from a network stream.

换句话说.您需要进行重定向,并将文件流写入HTTP响应,然后让用户决定要执行的操作:)

In other words. You'll need to do that redirect and write your file stream to the HTTP response and let the user decide what to do :)

这篇关于用ajax生成文件并允许用户下载它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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