简体   繁体   English

浏览器不生成文件下载对话框

[英]Browser does not generate file download dialog

My current scenario is that the JavaScript client has a bunch of data that I POST to the server to process/translate into different formats (eg CSV), now I want to send that transformed data from the server to the client. 我目前的情况是JavaScript客户端有一堆数据,我POST到服务器处理/转换成不同的格式(例如CSV),现在我想将转换后的数据从服务器发送到客户端。

I set the content type of the response, but the browser does not generate a file dialog. 我设置了响应的内容类型,但浏览器不生成文件对话框。

Here is what my controller looks like: 这是我的控制器的样子:

@RequestMapping(value="/exportBoxes/{type}/{filename:.+}", method=RequestMethod.POST)
public String exportBoxes(@RequestBody String body,      @PathVariable String type,
                          @PathVariable String filename, HttpServletResponse response) throws IOException
{
    JsonObject jsonObject = new JsonParser().parse(body).getAsJsonObject();

    //grab the data from the JSONobject
    String data = jsonObject.get("JSONdata").getAsString();

    //create output stream writer
    PrintWriter p = new PrintWriter(response.getOutputStream());

    //set response type and print header
    if(type.equals("csv"))
    {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    }

    //print the points to the file
    for(int i = 0; i < splitPoints.length; i++)
    {
        //print remainder of CSV file - abstracted
    }

    p.flush(); //flush the stream
    response.flushBuffer();
    p.close(); //close the stream

    return "success";
}

And here is the client function that POSTs the data: 这是POST数据的客户端函数:

DAService.prototype.exportBoxes = function(type, filename, data) {
    var path       = 'api/rest/da/exportBoxes/' + type + '/' + filename
    var url        = (this.connection) ? this.connection + path : path;
    var JSONdata   = '';
    var returnType = ''

    //create JSON string to pass to Java controller
    if(type == 'csv')
    {
        JSONdata   = '{ "JSONdata" : "' + data.replace(/ /g, '') + '" }';
        returnType = 'text/csv';
    }
    else
    {
        throw "Invalid export format " + type;
    }

    $j.ajax({
        url:         url,
        contentType: 'application/json',
        type:        'POST',
        dataType:    returnType,
        data:        JSONdata,
        success: function(returnedData){
            console.log("exportBox successful");
        },
        error: function(x,y,z) {
            console.log("exportBox failed with error '" + y + "'");
        },
        complete: function(empty, textStatus){
            console.log("exportBox complete textStatus='" + textStatus + "'");
        }
    });
};

No errors are generated by this code and the server's response has the CSV file in it, I just can't get the client to generate the download dialog. 此代码没有生成错误,服务器的响应中包含CSV文件,我无法让客户端生成下载对话框。

There is one piece that I am missing that I don't see, can anyone help me out? 我遗失了一件我看不到的东西,有人可以帮帮我吗?

You might want to try posting a form instead of using $.ajax : 您可能想尝试发布表单而不是使用$.ajax

var form = $('<form/>', {
  action: url,
  method: 'POST',
  css: { display: 'none' },
  html: $('<input/>', {name: 'JSONdata', value: data.replace(/ /g, '') })
});
$('body').append(form);
form.submit();

(I haven't tested that.) The point is that when you really post a form, the browser knows to interpret the response body, and it should notice your attachment. (我没有测试过。)关键是当你真正发布一个表单时,浏览器知道解释响应主体,它应该注意你的附件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM