Alon
Alon

Reputation: 7758

How do I allow the user to upload file to my site, edit it and save it back

I have a very simple web app I am building. no php - just html & javascript.

I want to get this use case for user who comes to my site:

  1. the user will choose a text file from his/her computer - for example: c:\directory\file.txt
  2. he will open this file in my webpage (do I have to use php for this? to upload the file to the server and then display it on my website? If I don't want the data in my server - just to let the user edit it - can I just do all these actions with js on client-side?)
  3. he will edit some of the text
  4. he will press a button called "save" or "save as" and it will automatically save his file in his computer.

since I am clueless in file management - I'd be happy to get a tip where to start advice on js libraries that manage that or general information about that.

thank, Alon

p.s searching the web for "upload files" gave me a lot of result on how to upload files to ftp - my question is not about that.

Upvotes: 3

Views: 1716

Answers (1)

Jeroen
Jeroen

Reputation: 63719

What you seem to be asking for typically requires server side code like php.

Having said that, there are some ways to do this with just JavaScript. The code will be largely browser-specific and generate a security warnings when saving (as it's typically unsafe to let JavaScript use resources like this). Specifically, I remember TiddlyWiki, which works with just JavaScript and HTML. Have a look at the code in such a TiddlyWiki file, there's code in there like this:

// Returns null if it can't do it, false if there's an error, true if it saved OK
function mozillaSaveFile(filePath,content)
{
    if(window.Components) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(filePath);
            if(!file.exists())
                file.create(0,0x01B4);// 0x01B4 = 0664
            var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
            out.init(file,0x22,0x04,null);
            out.write(content,content.length);
            out.flush();
            out.close();
            return true;
        } catch(ex) {
            return false;
        }
    }
    return null;
}

As an alternative, depending on the browsers you need to support, you could look into HTML5's local storage capabilities.

Upvotes: 1

Related Questions