19

I am new to javascript and I am currently having problem with one of my projects which includes viewing of an image from the root folder of the website. Here is my current code:

var reader = new FileReader();

    reader.onload = function(event){
           var dataUri = event.target.result,
               img = document.createElement("img");

               img.src =  dataUri;
               document.body.appendChild(img);
    };

    reader.onerror = function(event){
           console.log("File could not be read: " + event.target.error.code);
    };

reader.readAsDataURL("/uploads/extras/item_a/image1.png");

That's my code and it doesnt show anything. And in my console it gives me an error or Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

Trish Siquian
  • 495
  • 3
  • 11
  • 22
  • Anything showing in the console? – NewToJS Feb 28 '17 at 01:43
  • `GET data: net::ERR_INVALID_URL` @NewToJS – Trish Siquian Feb 28 '17 at 01:44
  • Try `/uploads/extras/item_a/image1.png` ? What's your folder structure like? – iflp Feb 28 '17 at 01:48
  • 2
    The console error is saying that `reader` is not happy with the `url`. Try hard coding the entire path to the file i.e `http://example.com/uploads/extras/item_a/image1.png` to rule out other issues. – JohanP Feb 28 '17 at 01:49
  • I got `Failed to load resource: net::ERR_INVALID_URL` @0019 – Trish Siquian Feb 28 '17 at 01:50
  • The error is very specific. new File needs at least 2 arguments. Check out this thread http://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript – Mehdi Feb 28 '17 at 01:51
  • What is `newFile` function ? Also, I highly suspect this function works asynchronously, which means that `myfile` will be undefined, or at least not the file you wanted. Finally, if what `newFile` does return is a File object, or a blob, use `URL.createObjectURL(myfile)` instead of an FileReader. – Kaiido Feb 28 '17 at 01:53
  • I dont know. What if I remove the `var myfile`? What will I put in my `reader.readAsDataURL(?);` – Trish Siquian Feb 28 '17 at 01:55
  • You don't show us what is this `newFile` function so we can't know what it expects, nor what it returns. (if for whatever reason it was a typo and you meant the `new File()` constructor, then it's absolutely not how it does work, since this conctructor needs a Blob object as first parameter and optionally a fileName string as second, but never an url. And you don't even need to create a File object, since what you can do with a File can be done with a Blob directly) – Kaiido Feb 28 '17 at 01:56
  • I tried to remove the `var myfile = newFile([""],"uploads/extras/item_a/image1.png");` and add `reader.readAsDataURL("uploads/extras/item_a/image1.png");` and it gives me a message of : `Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. ` – Trish Siquian Feb 28 '17 at 02:04
  • Yes because neither FileReader, nor `new File` do fetch data whatsoever. So if you're ok with ES6 (only new browsers), you can somehow achieve what you want with `fetch("uploads/extras/item_a/image1.png").then(r=>r.blob()).then(blob=>{let img = new Image(); img.src = URL.createObjectURL(blob); document.body.appendChild(img)})`. For es5 way, you'd have to use an XHR. Also, since you don't show us what you want to do with the file, it really unclear why you can't just do `img.src = "uploads/extras/item_a/image1.png"`. – Kaiido Feb 28 '17 at 02:13

5 Answers5

31

Here's the correct way to do it

var openFile = function(file) {
  var input = file.target;
  var reader = new FileReader();
  reader.onload = function(){
    var dataURL = reader.result;
    var output = document.getElementById('output');
    output.src = dataURL;
  };
  reader.readAsDataURL(input.files[0]);
};
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output' style="height:100px; width:100px;">

Do a little investigation to know where is the error in your code, that's better to learn

When you give it up, just leave a comment here, i'll be glad to help again! :)

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
El Don
  • 902
  • 7
  • 14
  • 2
    Thanks! But, I dont wan to use `` tag. I want to read it manualy. – Trish Siquian Feb 28 '17 at 01:54
  • 5
    No the correct way is `output.src = URL.createObjectURL(input.files[0]);`. But OP is trying to load a file from an url, not from a file input. – Kaiido Feb 28 '17 at 01:54
  • @TrishSiquian you simply can't do it that way, it's browser's security that will prevent you. – El Don Feb 28 '17 at 02:02
  • @Kaiido she's trying to load from a local file, which is not possible, if she's loading from url (http/s or anything not file:///) she'd rather use img tag what is it for if she doen't!! – El Don Feb 28 '17 at 02:05
  • @OmarElDon, I do agree it's not clear what OP is trying to do, but still, my point is that your way of displaying an input's file is not the *correct* one. And you'll agree that your answer doesn't answer the question anyway. And OP never talked about local file (from the file:// protocol) so XHR would work, and `img.src = url` would work too. – Kaiido Feb 28 '17 at 02:15
  • @Kaiido both ways lead to our Rome you see! `reader.result` and `URL.createObjectURL(input.files[0])` give the needed url... as the file reader will create the url and store it in it's result – El Don Feb 28 '17 at 02:33
  • @OmarElDon, but your way is like going from Napoli to Rome by São Paulo... It's asynchronous for nothing, and pollute the memory with 1.3 time the file content. While `URL.createObjectURL` is synchronous and is just a direct pointer to the file stored in the user hard-drive. – Kaiido Feb 28 '17 at 02:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/136802/discussion-between-omar-el-don-and-kaiido). – El Don Feb 28 '17 at 02:38
  • @Kaiido the result value will be created anyway and it's equal in size to URL's created object... The time needed is like 20µs for both... where is the big deal that should make one worry to use the first or the other – El Don Feb 28 '17 at 02:42
3

Here is the code that I have written to display the images from the file system in HTML and Javascript.

var inputSelectionHandler = function(event) {

            var reader = new FileReader();
            reader.readAsDataURL(event.srcElement.files[0]);
            reader.onload = function() {
                var fileContent = reader.result;
                var div = document.createElement("div");
                div.style.backgroundImage = "url(" + fileContent + ")";
                var btn_trigger = document.getElementById("btn_trigger");
                var file_btn = btn_trigger.parentElement;
                file_btn.insertBefore(div, btn_trigger);
            }

}
Raj Hirani
  • 182
  • 1
  • 5
0

It seems you are trying to load an image for use in Javascript without putting it in your HTML. You can do this by creating an image element in your Javascript and setting it's source. This won't be displayed on your site unless you insert it somewhere.

var image = document.createElement("img");
image.src = "file_path.png";

If you wish to access a file not on your website's folder but on whoever is running the website's machine by filepath, Javascript prevents you from doing this due to security reasons. (Imagine a website being allowed to access any file on your computer without you knowing!) You must use the <input type="file"> tag.

Luke
  • 9
  • 1
0

Here is an example of jquery way.

HTML:

<input type="file" class="form-control-file" id="fileinput" />
<img id="output" class="" src="" />

JQUERY:

$(document).ready(function(){

    $('#fileinput').change(function(e){
        var input = e.target;
        var reader = new FileReader();
        reader.onload = function(){
            $('#output').attr('src', reader.result);            
        };
        reader.readAsDataURL(input.files[0]);           
    });

});
infomasud
  • 2,263
  • 1
  • 18
  • 12
0

MDN Docs have a snippet about this:

function previewFile() {
  const preview = document.querySelector('img');
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  reader.addEventListener("load", () => {
    // convert image file to base64 string
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
<input type="file" onchange="previewFile()" /><br />
<img src="" height="200" alt="Image preview" />
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76