我現在的情況是,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文件,我只是無法讓客戶端生成下載對話框。
有一塊,我很想念我看不出來,誰能幫助我嗎?
也許嘗試'application/octet-stream'作爲內容類型。 – nkr 2012-07-11 17:47:17
@nkr也沒有生成文件對話框。 – 2012-07-11 17:49:36
如果不是使用'$ .ajax',而是將表單發佈到隱藏的'