如何使用 Jquery 创建 .txt 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17205676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:37:54  来源:igfitidea点击:

How can I create a .txt file using Jquery?

javascriptjqueryfile

提问by diego

Ok, this is my domain: example.com/index.html and I want to create a .txt file into the domain. result: example.com/file.txt with this info:

好的,这是我的域:example.com/index.html,我想在域中创建一个 .txt 文件。结果:example.com/file.txt 包含以下信息:

.js:

.js:

$('.saveButton').on('click', function (e) {
    e.preventDefault();
    $('.HTMLcontentTosave').html(); //save this html content into a file.txt
});

$.ajax maybe?

$.ajax 也许?

Thanks a lot!

非常感谢!

采纳答案by ctcherry

Using only jQuery/javascript in the browser, and a typically configured web server, this isn't possible. The filesystem of the server is not exposed in such a way that it is directly writeable from a client, that would be a rather large security risk.

在浏览器中仅使用 jQuery/javascript 和典型配置的 Web 服务器,这是不可能的。服务器的文件系统没有以可以从客户端直接写入的方式公开,这将是一个相当大的安全风险。

To make it possible, you will need to employ some server side code, such as PHP to assist in writing the file on the server. At that point you can send the desired content, and name of the file as a request to the server side code and that code can then write it to your desired location on the server's file system.

为此,您需要使用一些服务器端代码(例如 PHP)来协助在服务器上编写文件。此时,您可以将所需的内容和文件名称作为请求发送到服务器端代码,然后该代码可以将其写入服务器文件系统上的所需位置。

Make sure to employ adequate protections so only certain (safe) files can be written to, by the certain users you specify, otherwise you could open the previously mentioned security hole.

确保采用足够的保护措施,以便您指定的某些用户只能写入某些(安全)文件,否则您可能会打开前面提到的安全漏洞。

回答by Vandesh

Does this help you?

这对你有帮助吗?

Saving a text file on server using JavaScript

使用 JavaScript 在服务器上保存文本文件

Also, you can go through this one.

此外,你可以通过这个

回答by Brett Zamir

Technically, the "right" way would be to make a PUT request (the "type" argument: see http://api.jquery.com/jQuery.ajax/), but this is apparently not supported on all browsers, and some servers may also block these by default so you'd need to get around this. I say the "right" way because a PUT request is intended to mean that the consequence will be to save a file at the pointed location.

从技术上讲,“正确”的方法是发出 PUT 请求(“类型”参数:参见http://api.jquery.com/jQuery.ajax/),但这显然不是所有浏览器都支持,有些默认情况下,服务器也可能会阻止这些,因此您需要解决这个问题。我说“正确”的方式是因为 PUT 请求旨在意味着结果将是在指定位置保存文件。

The more common approach would be to allow a POST request but you'd need a server-side script to do things like validate that a user had permission to make the request.

更常见的方法是允许 POST 请求,但您需要一个服务器端脚本来执行诸如验证用户是否有权发出请求之类的操作。