从内存下载表单数据到本地计算机。

huangapple go评论57阅读模式
英文:

Download form data to local machine from memory

问题

这个问题的主要目标是在不先将表单数据写入服务器上的文件的情况下,直接将数据创建为一个下载表单,使用户可以在稍后上传到服务器时将其保存到本地机器上。您已经将表单数据编码为JSON格式,但是希望找到一种不必先将其写入服务器上的文件而直接下载的方法。

以下是代码部分,不做翻译:
$json_data=json_encode($data);

要实现这个目标,您可以使用JavaScript来创建一个包含表单数据的Blob对象,并将其提供给“save as”对话框,以便用户可以将数据保存到本地机器上。以下是一个示例代码片段,用于实现这一目标:

// 假设您已经有一个包含JSON格式的表单数据的变量 jsonData
var jsonData = /* 在这里插入JSON数据 */;

// 创建一个Blob对象
var blob = new Blob([jsonData], { type: 'application/json' });

// 创建一个下载链接
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'form_data.json'; // 设置下载文件的名称

// 模拟用户点击下载链接
a.click();

// 清理URL对象,以释放资源
URL.revokeObjectURL(a.href);

这段JavaScript代码将创建一个包含表单数据的Blob对象,并为其设置一个下载链接,以便用户可以点击下载。用户将能够将数据保存到本地机器上,而不需要在服务器上创建临时文件。

英文:

Is it possible to create a download form data to local machine without writing it to a file one the server?

I want to click export button on form and have "save as" file dialog popup, that would let me save the form data to my local machine with a view to upload it back to server at some later stage.
I want to do this without saving the form data to a file on the server and then downloading it.

I have encoded form data into json format.
$json_data=json_encode($data);
I just can't find a way to download this without writing it to a file on the server first.

答案1

得分: 1

我只是找不到不先将其写入服务器上的文件而下载它的方法。

实际上,情况有点相反:如果您查看有关使用PHP发送下载的任何说明,比如https://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header/8485963#8485963,您将看到实际文件的内容需要被读取并回显到浏览器。通常情况下,可以使用便捷函数readfile来完成此操作,但这只是echo file_get_contents($filename);的更高效版本。

如果您在字符串中有一些内容,并将其回显,浏览器无法知道您是否首先将其写入了服务器上的文件;它看到的输出完全相同。它将查看来决定是显示还是提示保存的是头部,特别是Content-TypeContent-Disposition头部。

英文:

> I just can't find a way to download this without writing it to a file on the server first.

It's actually kind of the opposite: if you look at any instructions on using PHP to send a download, such as https://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header/8485963#8485963 you will see that the actual content of the file needs to be read and echoed to the browser. Often this is done with the convenient function readfile, but this is just a more efficient version of echo file_get_contents($filename);

If you have some content in a string, and you echo it, the browser has no way of knowing whether you wrote it to a file on your server first; it sees the exact same output. The thing that it will look at to decide whether to display it or prompt to save is the headers, particularly the Content-Type and Content-Disposition headers.

huangapple
  • 本文由 发表于 2023年7月10日 14:15:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定