浏览器不生成文件下载对话框
Browser does not generate file download dialog
我当前的场景是JavaScript客户端有一堆数据,我将这些数据POST到服务器以处理/转换为不同的格式(例如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";
}
这里是发布数据的客户端功能:
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文件,我只是无法让客户端生成下载对话框。
我缺了一件我看不见的东西,有人能帮我吗?
您可能需要尝试张贴表单,而不是使用$.ajax
:
var form = $('<form/>', {
action: url,
method: 'POST',
css: { display: 'none' },
html: $('<input/>', {name: 'JSONdata', value: data.replace(/ /g, '') })
});
$('body').append(form);
form.submit();
(我还没有测试过。)关键是,当你真正发布表单时,浏览器知道如何解释响应主体,它应该注意到你的附件。
相关文章:
- 是否可以用JavaScript显示等效的文件夹对话框
- HTML”;文件“/OpenFile对话框解决方法
- Chrome、Firefox转换“:"至“-"以及“_"分别显示在文件保存对话框中
- 浏览器不生成文件下载对话框
- 当'文件打开对话框'弹出
- 使用 JavaScript 打开“另存为”/“下载”对话框以下载动态创建的文件
- 如何显示来自 Chrome 扩展程序的文件保存对话框
- 内容处置:附件未触发下载对话框
- 通过websocket接收文件并启动下载对话框
- Ext JS4如何从菜单打开文件打开对话框
- 下载zip文件并触发“;保存文件“;对话框的角度方法
- 我如何知道jquery中是否确认了文件打开对话框
- 触发文件输入对话框
- 使用iFrame显示下载对话框
- 如何过滤输入类型=“;文件“;对话框
- 文件打开对话框不工作在Chrome扩展
- 为什么在FireFox中单击按钮时文件打开对话框会打开两次?
- 为什么IE在GWT中不显示PDF文件下载对话框?
- 另存为文件下载对话框不工作在chrome
- 单击下载链接并出现文件保存对话框时触发的事件