2014-06-10 154 views
1

我正在做一个POST调用到我的服务器响应类型arraybuffer,它是目前返回与下面的头一个PDF斑点:触发的网页浏览器下载

"Content-Type": "application/pdf" 
"Content-Transfer-Encoding": "binary" 
"Content-Disposition": "attachment;filename=file.pdf\" 

我然后创建一个blob网址从响应:

var url = URL.createObjectURL(blob); 

有没有什么办法可以触发文件下载这个blob的工作跨浏览器?我想要标准文件下载发生,就好像用户点击了一个链接,例如<a href="/file.pdf"></a>

我已经试过:

  • 使用URL作为SRC一个脚本标记,它得到的斑点,但没有下载
  • 使用它作为URL在iFrame
  • 使用它作为对象和嵌入标签的数据url,但它显示的是对象而不是下载它
+0

我认为这能解决你的问题,至少在Chrome:http://stackoverflow.com/questions/6468517/force-download-of-datatext-plain-url – flamingcow

+0

这需要用户点击一个第二个链接,并且在IE中不起作用,所以这不能解决我的问题。 – Bill

回答

1

这就是我最终解决问题的方式。我使用生成文档所需的数据创建一个新表单,将表单的目标设置为我创建的iframe,然后提交表单。这会导致文件被正确下载。然后我最终使用服务器设置的cookie来确定下载何时完成。

var token = "my-form"; 

var form = document.createElement('form'); 
form.setAttribute('method', 'post'); 
form.setAttribute('target', token); 
form.setAttribute('action', "/my_target_url"); 

var hiddenField = document.createElement('input'); 
hiddenField.setAttribute('type', 'hidden'); 
hiddenField.setAttribute('name', 'data'); 
hiddenField.setAttribute('value', JSON.stringify(data_to_submit)); 
form.appendChild(hiddenField); 
element.append(form); 

var frame = document.createElement('iframe'); 
frame.setAttribute('id', token); 
frame.setAttribute('name', token); 
frame.setAttribute('src', ''); 
frame.setAttribute('style', 'width:0;height:0;border:0px solid #fff;'); 
element.append(frame); 

form.submit(); 
相关问题