如何使用JavaScript写入文件(用户目录)? [英] How to Write in file (user directory) using JavaScript?
问题描述
我试过FileSystem API,我试过的代码是使用html5和javascript或jquery写入chrome(所有版本)的任何文件的txt。 :
函数onFs(fs){
console.log('test');
fs.root.getFile('log.txt',{create:true,exclusive:true},
function(fileEntry){
// fileEntry.isFile === true
// fileEntry.name =='log.txt'
// fileEntry.fullPath =='/ log.txt'
fileEntry.getMetaData(function(md){
console.log(md.modificationTime.toDateString());
},onError);
},
onError
);
}
window.webkitRequestFileSystem(TEMPORARY,1024 * 1024 / * 1MB * /,onFs);
但不能正常工作。
有什么方法可以写入文件?
我想在用户目录中写入文件
你不能直接将文件写入用户文件系统。
在搜索SO之后类似准确解决问题的问题能够在创建的文件内容 $ cat
@Iain在在哪里发布>答案带有chrome的PERSISTENT文件系统存储库?。该文件被写入到〜/ .config / [chrome,chromium]
目录下的用户文件系统中。
已使用文件管理器导航到
〜/ .config / [chrome,chromium] /默认/文件系统
code>
查看目录;包含以下文字的文件在包含两个数字作为文件夹名称的文件夹中找到,然后在另外两个子目录中找到;一个子目录,只有一个小写字母作为文件夹名称;在这个子目录中有另一个子目录,其中有两个数字作为文件夹名称;由 window.webkitRequestFileSystem
编写的文件有八位数字作为文件名,没有扩展名,虽然有正确的text / plain code> MIME类型;设置为
Blob
输入
属性。
然后在终端
< code $ cd〜/ .config / [chrome,chromium] / Default / File\ System / [三位数字] / [小写字母] / [两位数字]
$ cat [八位数]
Lorem Ipsum
没有尝试创建 .sh
文件并执行它。可能需要将目录放置在路径
中,或将文件移动到现有的路径
中的文件夹中;为文件设置适当的权限
。可能可以在Chrome浏览器/铬浏览器设置中调整此设置,尽管还没有尝试过。
您可以写一个命令将 / path / to / file
中的文件复制或移动到文件夹在路径
中,并执行该文件;或其他方法。
您可以使用下载
属性 a
元素允许将由 createWriter
创建的文件下载到用户文件系统。
由于文件系统是沙盒式,所以web应用程序无法访问另一个
app的文件。您也无法将文件读取或写入用户硬
驱动器上的任意
文件夹(例如,我的图片和我的文档)。
另见 Definititons
持久存储空间持久存储是指保留在浏览器中的存储空间,除非用户将其删除或该应用程序将其删除。
临时存储空间任何网络应用均可使用暂时存储空间。它是自动的,不需要被请求,但浏览器可以在
没有警告的情况下删除存储。
我想在用户目录中写入文件,因为它必须是用户
可以理解的。
编辑,更新
您可以使用上述方法。也就是说,使用文件管理器查看文件夹和文件的显示方式
〜/ .config / [chrome,chromium ] /默认/文件系统
##用`window.requestFilesystem`写的文件内容做东西
要在chrome / chromium FileSystem
中查看文件,您可以导航到 DevTools - >
实验
- >检查 FileSystem检查,
log .txt
应列于资源
选项卡上 FileSystem
中。
也可以使用URL导航到地址栏中的文件
文件系统:http://run.plnkr.co/temporary/log.txt
哪些内容
Lorem Ipsum
或
文件系统:http://run.plnkr.co/temporary/
查看临时文件系统根目录下的所有文件和目录
a href =http://html5rocks.com/en/tutorials/file/filesystem =nofollow noreferrer>探索FileSystem API
首先使用 下一个 添加错误处理 您应该可以 plnkr http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview 请注意,在Chrome 38+中,也可以使用 不,这是后台进程,将数据保存到 这种方法也不会自动将创建的文件写入用户文件系统的现有文件夹。 无论采用哪种方法,都需要用户操作将文件保存到用户文件系统。这可以使用 - 允许文件访问文件
标志启动chrome / chromium,参见
窗口。 requestFileSystem = wind ow.requestFileSystem
|| window.webkitRequestFileSystem;
函数errorHandler(e){
var msg ='';
switch(e.message){
case FileError.QUOTA_EXCEEDED_ERR:
msg ='QUOTA_EXCEEDED_ERR';
休息;
case FileError.NOT_FOUND_ERR:
msg ='NOT_FOUND_ERR';
休息;
case FileError.SECURITY_ERR:
msg ='SECURITY_ERR';
休息;
case FileError.INVALID_MODIFICATION_ERR:
msg ='INVALID_MODIFICATION_ERR';
休息;
case FileError.INVALID_STATE_ERR:
msg ='INVALID_STATE_ERR';
休息;
默认值:
msg ='未知错误';
休息;
};
console.log('Error:'+ msg);
}
函数writeFile(fs){
fs.root.getFile('log.txt',{create:true},function(fileEntry) {
//为我们的FileEntry(log.txt)创建一个FileWriter对象。
fileEntry.createWriter(function(fileWriter){
fileWriter.onwriteend = function (e){
console.log('写完成。');
//调用`readFile`这里
window.requestFileSystem(window.TEMPORARY,1024 * 1024,readFile,errorHandler) ;
};
fileWriter.onerror = function(e){
console.log('Write failed:'+ e.toString());
};
//创建一个新的Blob并将其写入log.txt。
var blob = new Blob(['Lorem Ipsum'],{type:'text / '));
fileWriter.write(blob);
,errorHandler);
},errorHandler);
window.requestFileSystem(window.TEMPORARY,1024 * 1024,writeFile,errorHandler);
函数readFile(fs){
fs.root.getFile('log.txt',{},函数(fileEntry){
//获取表示文件的File对象,
//然后使用FileReader读取它的内容。
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend =函数(e){
console.log(e.target.result)
};
reader.readAsText(file) ;
},errorHandler);
},errorHandler);
新文件创建
构造函数;请参阅 Chrome:使用Javascript从blob创建文件输入? 。 File
对象()
文件夹中的文件中。
a
元素的 download
属性来实现,数据URI
如何将JavaScript数组信息导出到csv (在客户端)?,或 iframe
元素使用Javascript / jQuery下载文件
I want to write into txt of any file from chrome(All version) using html5 and javascript or jquery.
I have tried FileSystem API and code I tried is:
function onFs(fs) { console.log('test'); fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) { // fileEntry.isFile === true // fileEntry.name == 'log.txt' // fileEntry.fullPath == '/log.txt' fileEntry.getMetaData(function(md) { console.log(md.modificationTime.toDateString()); }, onError); }, onError ); } window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs);
But not working.
Is there any way to write into the file?
I want to write file in user directory
You cannot directly write file to user filesystem .
After searching SO for similar Questions to accurately resolve Question, was able to $ cat
contents of file created at plnkr following this answer posted by @Iain at Where does PERSISTENT file system storage store with chrome? . The file was written to the user filesystem at ~/.config/[chrome, chromium]
directory.
Used file manager to navigate to
~/.config/[chrome, chromium]/Default/File System
to review the directory; the file containing text written below, was found in a folder having two digits as a folder name, then within two further sub-directories; a sub-directory having a single lowercase letter as folder name; within this sub-directory there was another sub-directory having two digits as a folder name; the file that was written by window.webkitRequestFileSystem
had eight digits as a file name, without an extension, though having correct "text/plain"
MIME type; set at Blob
type
property.
Then at terminal
$ cd ~/.config/[chrome, chromium]/Default/File\ System/[three digits]/[lowercase letter]/[two digits]
$ cat [eight digits]
Lorem Ipsum
Have not tried to create a .sh
file and execute it. Would probably require placing the directory in path
or moving the file to a folder in existing path
; set appropriate permissions
for file. Could possibly adjust this at chrome / chromium browser settings, though have not tried this either.
You could probably write a command to copy or move the file at /path/to/file
to an folder in path
, and execute the file; or other approach.
You can use download
attribute of a
element to allow download of file created by createWriter
to user filesystem.
Because the file system is sandboxed, a web app cannot access another app's files. You also cannot read or write files to an arbitrary folder (for example, My Pictures and My Documents) on the user's hard drive.
see also at Definititons
persistent storage Persistent storage is storage that stays in the browser unless the user expunges it or the app deletes it.
temporary storage Transient storage is available to any web app. It is automatic and does not need to be requested, but the browser can delete the storage without warning.
I want to write file in user directory because it has to be user understandable.
Edit, Updated
You can use the method described above. That is, use a file manager at to review how the folders and files appear in
~/.config/[chrome, chromium]/Default/File System
## do stuff with contents of file written by `window.requestFilesystem`
To view file in chrome / chromium FileSystem
you can navigate to DevTools
-> Experiments
-> check FileSystem inspection
, log.txt
should be listed at Resources
tab at FileSystem
.
Can also navigate to file at address bar using URL
filesystem:http://run.plnkr.co/temporary/log.txt
which should have contents
Lorem Ipsum
or
filesystem:http://run.plnkr.co/temporary/
to view all files and directories in root of temporary filesystem
See Exploring the FileSystem API
First launch chrome / chromium with --allow-file-access-from-files
flag , see How do I make the Google Chrome flag "--allow-file-access-from-files" permanent? .
Next
window.requestFileSystem = window.requestFileSystem
|| window.webkitRequestFileSystem;
add error handling
function errorHandler(e) {
var msg = '';
switch (e.message) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
You should then be able to
function writeFile(fs) {
fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
// call `readFile` here
window.requestFileSystem(window.TEMPORARY, 1024*1024, readFile, errorHandler);
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.TEMPORARY, 1024*1024, writeFile, errorHandler);
function readFile(fs) {
fs.root.getFile('log.txt', {}, function(fileEntry) {
// Get a File object representing the file,
// then use FileReader to read its contents.
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(e.target.result)
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
plnkr http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview
Note, at Chrome 38+ it is also possible to create a File
object using the new File()
constructor; see Chrome: Create file input from blob with Javascript? .
No, It is background process, save the data into the file exist in folder.
This approach, too, will not automatically write created file to an existing folder at user filesystem.
With either approach user action should be required to save file to user filesystem. This can be achieved using download
attribute at a
element , data URI
How to export JavaScript array info to csv (on client side)? , or an iframe
element Download File Using Javascript/jQuery ; which should prompt user to either select to save file or not save file.
See also The FileSaver interface , FileSaver.js
这篇关于如何使用JavaScript写入文件(用户目录)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!