11

(Am new to web programming, so apologies for any lack of rudimentary knowledge.)

My page allows a user to select a file that is then read clientside & displayed in a textbox on the page. The easiest way I found to do this was to use a FileReader object, which works fine in Firefox and Chrome.

This doesn't work in Safari (yet), so what should I do instead?

//When the eventlistener detects a change in the input file...
var file = evt.target.files[0]
var reader = new FileReader();
reader.onload = function (e){document.getElementById('data').value = e.target.result};
reader.readAsText(file);

Relevant Notes:

  • I'm working with Safari for windows
  • Right now the page is local as is the file to read. Chrome had issues with this until I used the flag --allow-file-access-from-files
Emma
  • 113
  • 1
  • 2
  • 5

2 Answers2

8

Sadly, the only answer I can come up with will hog some extra bandwidth.

Firstly, use something like if (typeof FileReader !== "undefined" or Modernizr to follow your normal flow for the browsers that DO support FileReader. Otherwise, POST the file via AJAX to some server-side script that echoes back the contents.

So for compliant browsers, you get to save yourself some bandwidth and for non-compliant browsers you have to take one for the team.

Quickredfox
  • 1,428
  • 14
  • 20
  • Maybe this would satisfy your need though: https://github.com/dcneiner/Downloadify – Quickredfox Nov 03 '11 at 14:35
  • Thanks! It felt silly, but I just didn't know what the alternative possibilities were (guess that happens when you're still new to everything!) – Emma Jan 25 '12 at 17:18
  • I really liked your answer, seems like a responsive way of handle this situations. Thank you. – Gaston Sanchez Aug 17 '13 at 22:51
  • @Quickredfox bro I have the same problem, I have understood the first part and it works perfect, But the ajax part is confusing me Do i need to send the whole input file in ajax? please explain in detail the following is my code function showimagepreview(input) { if(input.files && input.files[0]) { if (window.FileReader){ var fr=new FileReader(); fr.onload=function(e) { $("#image").attr('src',e.target.result); $("#storedProfileImage").attr('value',e.target.result); } fr.readAsDataURL(input.files[0]); } else{ alert(); console.log(input.files); }} } –  Sep 07 '15 at 13:11
1

Another solution is to use "A FileReader polyfill for Internet Explore and Safari using Flash"

See: https://github.com/Jahdrien/FileReader

Tony
  • 16,527
  • 15
  • 80
  • 134