简体   繁体   English

是否可以使用javascript将文件保存到当前文件所在的目录?

[英]It it possible to use javascript to save a file to same directory as current file?

I am writing JavaScript code which is executed in a local web server. 我正在编写在本地Web服务器中执行的JavaScript代码。 Is it possible to have that code generate another file, which is then added to the same directory as the original file? 是否可以使该代码生成另一个文件,然后将其添加到与原始文件相同的目录中? If so, how? 如果是这样,怎么办?

I am not an expert on this, but I will try to help out. 我不是这方面的专家,但我会尽力提供帮助。 From my understanding the only way to create a file on the server is to have server side code do it. 据我了解,在服务器上创建文件的唯一方法是让服务器端代码来执行此操作。 You could have the javascript call some endpoint and that could create the file. 您可以让javascript调用某个端点,然后可以创建文件。 But I believe it is impossible to directly create the file. 但是我相信不可能直接创建文件。

Things have greatly changed with HTML5 and so the answer is "Yes!" HTML5的情况发生了很大变化,因此答案是“是!”。 provided that one is using a modern browser and/or one takes advantage of JavaScript libraries that may aid with this endeavor. 前提是使用的是现代浏览器,并且/或者使用的JavaScript库可以帮助实现这一目标。 Take a look here as well as here . 看看这里这里 If you alter your browser's download settings to the desired folder of your local web server, when you submit the form the file will be downloaded there. 如果将浏览器的下载设置更改为本地Web服务器的所需文件夹,则在提交表单时,文件将被下载到此处。 I tried this using google chrome 49 on a windows box using wampserver and the file was saved exactly in the specified folder. 我在使用wampserver的Windows框上使用google chrome 49尝试了此操作,文件完全保存在指定的文件夹中。 After forking the code here , it ran successfully on my local webserver from the directory where I wanted the new file to be downloaded. 这里分叉代码之后,它已从我希望下载新文件的目录中成功在我的本地Web服务器上运行。

The pertinent jQuery code from codepen.io: 来自codepen.io的相关jQuery代码:

$("#btn-save").click( function() {
      var text = $("#textarea").val();
      var filename = $("#input-fileName").val()
      var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
      saveAs(blob, filename+".txt");
    });

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

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