dongpao1918 2018-03-24 10:02
浏览 61
已采纳

如何下载通过post生成的php文件,同时避免页面位置被更改?

I have a file download.php which I feed via post with data and then generates an svg file to download via setting the header with

header('Content-Type: application/svg+xml');
header("Content-Disposition: attachment; filename=\"myfilename\"");

Now, the question is how to initiate the download. My first attempt was to put the data into a form and submit it via post with

<form id="svgform" method="post" action="download.php" style="display: none;">
    ...
</form>

Normally, this works fine. It will not change the location to download.php but only initiate the download. Unfortunately, this method seems to have the caveat that (in the rare case) where the php request generates an error (for whatever reason), the page is changed. I want to avoid a page change at all cost (because unsaved data may be lost). It also has some other strange side-effects [1].

So, next I tried to initiate the download in a new tab via

<form id="svgform" method="post" target="_blank" action="download.php" style="display: none;">
    ...
</form>

This leads to an ugly white page popping up for a moment before the download starts. Even worse, in IE 11 the white page does not close and the download dialog lands on the previous page so the user does not see it immediately.

So, I am wondering what is the best way to go ahead. Could the download be better achieved via AJAX and how?

[1] For some reason, Firefox cannot generate html inspector data when the inspector has been opened before. Here is a way to see what I mean. Inspect some element in Firefox and leave the inspector open. Now, go to a page that downloads data via the method above (or similar), e.g. http://download.cnet.com/CCleaner/3001-18512_4-10315544.html. The inspector becomes empty and no element can be inspected anymore. Furthermore, some of my scripts stopped working properly in IE 11. I am not sure yet why maybe it is related to what happens in Firefox.

  • 写回答

1条回答 默认 最新

  • duanfeigui6655 2018-03-24 10:35
    关注

    Since you don't want to change the URL when posting the form but you still want a download to start, you can post the form an iframe instead.

    <form target="my-iframe-id" method="post" ... >
    

    and the iframe:

    <iframe id="my-iframe-id" ... ></iframe>
    

    You can set the iframe as display: none; so it doesn't show.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图