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.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊