Qvatra
Qvatra

Reputation: 3857

javascript fileReader alternative for safari(<6)

I'm developing a website that works offline(using cashe) on a client side.
I need to implement image upload to the LocalStorage via the website and then send it when the user will have access to the internet. To read image as URL I use FileReader BUT The problem is that most of the users will use Safari browser and there is no FileReader function in Safari(<6).

I read that it could be done via ajax post to a php script. The php script should echo back the content... but I need my website working offline so I think it's impossible to implement it via ajax.. Am I right?

how can I implement image reading in Safari browser?

Upvotes: 1

Views: 2808

Answers (1)

aecend
aecend

Reputation: 2462

Update:

You'll also need to include the swfobject script in your page for Flash fallback to work properly, its a dependency of the FileReader polyfill. You can go here to download the package.

Previous:

Here's a sample that demonstrates using the FileReader plugin. You'll need to use jQuery 1.x (jquery-1.11.3.min.js) to achieve the desired backwards compatibility:

<input type="file" id="files" name="files[]" multiple>
<div id="list"></div>

<script src="js/jquery.min.js"></script>
<script src="js/jquery.FileReader.min.js"></script>

<script>

$("#files").fileReader({
    filereader: "js/filereader.swf"
});

$("#files").on("change", function(evt) {

    for (var i = 0; i < evt.target.files.length; i++) {

        console.log(evt.target.files[i].name, evt.target.files[i].type, evt.target.files[i].size, evt.target.files[i].lastModifiedDate);

        var f = evt.target.files[i];
        var reader = new FileReader();

        reader.onload = (function(theFile) {

            return function(e) {

                // Render preview
                var span = document.createElement('span');
                span.innerHTML = '<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>';
                document.getElementById('list').insertBefore(span, null);

            };

        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);        

    }

});

</script>


Previous

You'll need to use a polyfill such as this FileReader plugin. It detects whether or not the user's browser has the FileAPI available, and if not, it uses Flash to emulate the now standard FileReader. Check out the documentation, but I'm fairly certain this is what you'll need.

I know you didn't have the question tagged with jQuery, but in order to use this polyfill it will be required, unless you're comfortable with adapting it to vanilla JavaScript.

Upvotes: 4

Related Questions