How to create a text file on a client machine using javascript or jquery

折月煮酒 提交于 2019-12-12 09:24:25

问题


How to create a text file on a client machine using javascript or jquery


回答1:


it is possible on IE and firefox... but wonder how it will work on Safari and Crome searching the same...

for FF

netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
// Open the save file dialog
var nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);

fp.init(window, "Save File...", nsIFilePicker.modeSave);
//fp.appendFilters(nsIFilePicker.filterHTML);
fp.appendFilter("HTML File","*.htm; *.html");
fp.defaultString="data.htm";

var rv = fp.show();
if (rv == fp.returnCancel) return;

if(rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace){
    // Open the file and write to it
    var file = fp.file;
    //var filePath = file.path+".htm";
    //  //file.initWithPath(filePath);

    if(file.exists() == false){//create as necessary
        file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
    }
    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                                          .createInstance( Components.interfaces.nsIFileOutputStream );
    outputStream.init( file, 0x04 | 0x08 | 0x20, 640, 0 );
    var result = outputStream.write( output, output.length );
    g.filename.value=file.path;
    outputStream.close();
    alert('File has been saved.' );
}

for IE

var w = window.frames.w;
if( !w ) {
    w = document.createElement( 'iframe' );
    w.id = 'w';
    w.style.display = 'none';
    document.body.insertBefore( w );
    w = window.frames.w;
    if( !w ) {
        w = window.open( '', '_temp', 'width=100,height=100' );
        if( !w ) {
            window.alert( 'Sorry, could not create file.' );
            return false;
        }
    }
}

var d = w.document;
d.open( 'text/xml', 'replace');
d.charset = "UTF-8";

d.write(JWPFormToHTML(f));
d.close();
var name= g.filename.value;

if( d.execCommand( 'SaveAs', false , name ) )
{
    g.filename.value=name;
    //document.getElementById("filename").value="";
    alert('File has been saved.' );
}
else
{
    alert( 'The file has not been saved.\nIs there a problem?' );
}
w.close();
return false;

EDIT

got it on safari and chrome as well you have to create a signed applet to create read and write files and access the local data using the same :P




回答2:


Not sure what your needs are exactly, but since it's not possible to write to a text file (other than cookies), could you use HTML 5 Web Storage? It's only supported in the latest browsers, see example usage here: http://davidwalsh.name/html5-storage



来源:https://stackoverflow.com/questions/4274456/how-to-create-a-text-file-on-a-client-machine-using-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!