简体   繁体   English

使用iframe下载文件

[英]Use iframe to download file

Currently, I'm downloading the file using POST form: 目前,我正在使用POST形式下载文件:

var form = document.createElement("form");
var element1 = document.createElement("input");
var element2 = document.createElement("input");

form.target = "_blank";
form.method = "POST";
form.action = path;

element1.value = authService.getToken();
element1.name = "Authorization";
form.appendChild(element1);

element.append(form);

form.submit();
element.empty();

In order to prevent current page's location change when the server doesn't send correct headers, I open set the form's target to "_blank", so that if an error occurs it is shown on the other page. 为了防止当服务器未发送正确的标题时当前页面的位置发生变化,我打开将表单的目标设置为“ _blank”,以便在发生错误时将其显示在另一页上。 But the problem here is that browsers block new tabs by default, and I don't want to force users to allow such behaviour. 但是这里的问题是,浏览器默认情况下会阻止新标签页,并且我不想强迫用户允许这种行为。 I've read that also there an option to specify iframe's id as a target. 我读过,还有一个选项可以将iframe的ID指定为目标。 Is it going to work in my case? 就我而言,这行得通吗? How can I then read an error from the iframe to show to a user? 然后,如何从iframe中读取错误并显示给用户?

I am working on this very problem right now. 我现在正在解决这个非常严重的问题。 The best answer I've found for returning state from the iframe is to set a cookie in it. 我发现从iframe返回状态的最佳答案是在其中设置一个cookie。 The cookie's name should ideally be unique to the particular download event (I'm using a guid), known to both pages, and its value can be an error message or empty for success. 理想情况下,cookie的名称对于两个页面都知道的特定下载事件(我使用的是guid)应该是唯一的,并且它的值可以是错误消息,也可以是空值(表示成功)。 The parent page then polls for this cookie in javascript. 然后,父页面会在javascript中轮询此Cookie。 I make sure that the download url always renders the cookie if there's an error, because it's hard to learn anything else about the state of the iframe. 如果出现错误,我确保下载URL始终呈现cookie,因为很难了解有关iframe状态的其他信息。 On success, the JS poller can hide a ”your download will begin shortly" message, and delete the cookie. On failure, do those and also show the error. 成功后,JS轮询器可以隐藏“您的下载即将开始”消息,并删除Cookie;失败时,执行这些操作并显示错误。

The big unanswered question is how well it'll work in mobile browsers. 一个悬而未决的大问题是,它在移动浏览器中的运行情况如何。 Popups are a terrible choice with them because they mostly default to blocking them with no prompt... but nevertheless there's a jQuery plugin out there for iframe downloads which, when it sees mobile, falls back to popups. 弹出式窗口是它们的一个糟糕选择,因为它们默认情况下默认为不提示即阻止它们……但是,尽管如此,仍有一个jQuery插件可用于iframe下载,当它移动时,它会返回到弹出窗口。 That scares me. 吓死我了

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

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