从阿贾克斯下载文件(之类的) [英] Download file from Ajax (sort of)

查看:125
本文介绍了从阿贾克斯下载文件(之类的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在GSP这个AJAX调用:

I have this ajax call in my GSP:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: data,
    success: function() {
        alert("Success");
    }
});

这是code座从我的控制器操作:

This is code block from my controller action:

response.setHeader("Content-disposition", "attachment; filename=sample.csv")
response.contentType = "application/vnd.ms-excel"

def outs = response.outputStream
def cols = [:]

tickets.each() {
    outs << it.ticketNo + ";" + it.subject
    outs << "\n"
}

outs.flush()
outs.close()

我得到了我通过从视图中通过$就法数据门票列表。比我格式化数据为CSV,比我想导出数据,CSV文件,但没有任何反应。该数据被发送到客户端,但没有下载的内容处置没有文件的格式不正确。我在想什么? 我一直试图做这样的事情:

I get tickets list from data that I pass from view via $.Ajax method. Than I format that data as CSV and than I want to export that data as CSV file but nothing happens. The data is send to client but there is no file for download as content-disposition is not well formed. What am I missing? I've tried to do something like:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: aoData,
    dataType: 'text',
    success: function(result) {
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
        window.open(uri, 'tiketi.csv');
    }
});

和控制器中我产生纯字符串,但这种方式,我得到一个文件,而不扩展,它是不可接受的。

and in controller I generate plain string, but that way I get a file without extension which is unacceptable.

我怎样才能做到这一点?谢谢你。

How can I achieve this? Thank you.

推荐答案

您不需要通过Ajax来做到这一点。该页面将不会重定向文件下载。

You dont need to do it via ajax. The page will not redirect for file downloads.

这篇关于从阿贾克斯下载文件(之类的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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