0

我是 MVC 的新手,并试图找出一种方法来执行以下操作:

基本上,我有一个 URL http://dev.test.com/api/data/abczyz12345,当从用户界面单击/打开时,结果显示为:

"email","f_name","l_name","c_name","ids" "abc1@test.com","C G","Wander","C1","" "abc2@Atest.COM","Virginia","Dale","A & D","" .... and so on....

在我看来,我将上面的链接显示为锚点,当用户点击它时 - 它会在同一页面上打开。有没有一种方法可以在用户单击链接时 - 而不是在网页上打开它,而是以 CSV 文件的形式打开(为用户提供下载选项)?

4

3 回答 3

1

是的,您必须指定使用 HTTP 标头的文件类型。这是一个使用 PHP 的示例:

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');

echo '"email","f_name"...

浏览器会将输出识别为 CSV 并做出相应响应,很可能会出现文件下载提示。

ASP.net 也是如此,但我不确定它是如何在那里完成的。

于 2012-04-25T19:38:07.203 回答
1
public ActionResult Index()
{
    Response.Clear();
    Response.Clear();
    Response.ContentType = "application/CSV";
    Response.AddHeader("content-disposition", "attachment; filename=\"filename.csv\"");
    String temp = "email,f_name,l_name,c_name,ids,abc1@test.com,CG,Wander,C1,abc2@Atest.COM,Virginia,Dale,A & D";
    Response.Write(temp);
    Response.End();
    return View();
}
于 2012-04-25T20:00:35.700 回答
0

有几种方法可以处理这个问题,我不能完全确定您的目标受众、环境以及您对这些数据的总体目标。

我将使用厨房水槽路线(您可以使用页面中的数据并允许将其导出到文件):

您可以使用 jquery 将数据包装到文件中以供下载。

本教程在服务器端使用 php,但如果我了解您的要求,您需要在客户端处理该数据:

http://tutorialzine.com/2011/05/generating-files-javascript-php/

请参阅以下部分:资产/script.js

摘抄:

$(document).ready(function(){

    $('#download').click(function(e){

        $.generateFile({
            filename    : 'export.txt',
            content     : $('textarea').val(),
            script      : 'download.php'
        });

        e.preventDefault();
    });

    $('#downloadPage').click(function(e){

        $.generateFile({
            filename    : 'page.html',
            content     : $('html').html(),
            script      : 'download.php'
        });

        e.preventDefault();
    });

});

动态生成文档的好小例子。

于 2012-04-25T19:41:50.527 回答