简体   繁体   English

下载使用POST数据即时生成的文件

[英]Download file generated on the fly using POST data

I need to generate a PDF file using some data I get from a POST request. 我需要使用从POST请求获得的一些数据生成PDF文件。 As response to this request, I want to send the generated PDF file, for which the user should get a "save file as"-dialog. 作为对此请求的响应,我想发送生成的PDF文件,对此用户应该获得“另存为”对话框。

This all should happen on the fly. 这一切都应该即时发生。 I don't want to save the PDF to the disk and serve it with an additional request. 我不想将PDF保存到磁盘上,但需要额外的请求。 It should all happen with one single request. 所有这些都应该在一个请求中发生。

But I don't know how I could achieve such a thing. 但是我不知道我怎么能做到这一点。 If I use a XMLHttRequest, I can't make the "save-file-as"-dialog appear. 如果使用XMLHttRequest,则无法显示“另存为”对话框。 On the other hand, if I use a form, I can't send the POST data without some URL-encryption overhead. 另一方面,如果使用表单,则没有一些URL加密开销就无法发送POST数据。

Does anyone have an idea? 有人有主意吗?

In the end, I solved it with 2 Requests. 最后,我用2个请求解决了它。 The first sends the needed data to the server and creates the PDF out of it, and then returns the ID of the temporary file. 首先将所需的数据发送到服务器,并从中创建PDF,然后返回临时文件的ID。 The second downloads the pdf and deletes the temporary file. 第二个下载pdf并删除临时文件。

I'm doing this by posting data from a javascript generated form-field to the php. 我这样做是通过将数据从javascript生成的表单字段发布到php来实现的。

var form = $('<form method="post" action="svgoutput/convert.php"> <input type="text"  name="incomingSvgData" value="'+base64_encode(svgDataString)+'"><input type="submit" value="Submit Post"> </form> ');
form[0].submit();

For IEs the form has be in the dom while submitting. 对于IE,提交时该表格已在dom中。

On php side I do my generation and stuff (SVG to PNG in this case) and set the following headers: 在php方面,我进行生成工作(在这种情况下为SVG到PNG),并设置以下标头:

header("Content-Type: YOURMIMETYPE");
header("Content-Disposition: attachment; filename=YOURFILENAME.EXT");
echo YOURDATA;

Downloads smoothly w/o even showing a save as dialog in just one post. 顺利下载,即使在一篇文章中也显示“另存为”对话框。 If you need the Save As just play around with the headers, like here How to show 'Save as' dialog box using PHP for text files 如果您需要“另存为”只需要处理标题,例如此处, 如何使用PHP显示文本文件的“另存为”对话框

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

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