2012-07-11 94 views
4

我现在的情况是,JavaScript客户端有一组数据,我发送到服务器来处理/转换成不同的格式(如CSV),现在我想从发送转换数据服务器到客户端。浏览器不产生文件下载对话框

我设置的内容类型的响应,但浏览器不会生成一个文件对话框。

这里是我的控制器看起来像:

@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"; 
} 

这里是客户端功能的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 + "'"); 
     } 
    }); 
}; 

没有错误是由这个代码生成和服务器的响应有其中的CSV文件,我只是无法让客户端生成下载对话框。

有一块,我很想念我看不出来,谁能帮助我吗?

+2

也许尝试'application/octet-stream'作为内容类型。 – nkr 2012-07-11 17:47:17

+0

@nkr也没有生成文件对话框。 – 2012-07-11 17:49:36

+0

如果不是使用'$ .ajax',而是将表单发布到隐藏的'