0

I have a script where I want the end user to be able to specify an image (using a file chooser) to change the site's background to. But I don't want them to actually upload the file to the server, as that would not only be redundant (as they would then just be re-downloading it when the background changes) but also impossible since it's a user script. Rather, I just want the background src to change to the local file path.

How is this best accomplished? The file chooser form element for some reason only gives javascript access to the filename and not the full path. I'm okay with using a different HTML element as long as the users don't have to type in the file path manually.

Joey
  • 10,504
  • 16
  • 39
  • 54
  • Possibly related: http://stackoverflow.com/questions/15201071/how-to-get-full-path-of-selected-file-on-change-of-input-type-file-using-jav – isherwood Mar 15 '14 at 17:14
  • 1
    Consider using local HTML storage: http://stackoverflow.com/questions/11582556/loading-an-image-to-localstorage-and-setting-an-image-src-to-that-location – isherwood Mar 15 '14 at 17:17

1 Answers1

2

You could use the FileReader API to encode an image to a data: URL and save that in the LocalStorage of the browser. However if a user clears the browser history the background will be lost too.

I've written some example code to get you started:

HTML

<input id="image-input" type="file">

JavaScript

var input = document.getElementById('image-input'),
    tag = document.getElementsByTagName('html')[0];

input.addEventListener('change', function() {

    var file = input.files[0],
        reader = new FileReader();

    if( !file ) {
        return;
    }

    reader.addEventListener('load', function( evt ) {

        localStorage['background-image'] = reader.result;

        tag.style.backgroundImage = 'url(' + reader.result + ')';

    });

    reader.readAsDataURL(file);

});

if( localStorage['background-image'] ) {
    tag.style.backgroundImage = 'url(' + localStorage['background-image'] + ')';
}

A JSFiddle is available here (note that I've commented out the localstorage code because it's not allowed in JSFiddle).

Jon Koops
  • 8,801
  • 6
  • 29
  • 51