21

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'.

11
  • Anything showing in the console? Commented Feb 28, 2017 at 1:43
  • GET data: net::ERR_INVALID_URL @NewToJS Commented Feb 28, 2017 at 1:44
  • Try /uploads/extras/item_a/image1.png ? What's your folder structure like? Commented Feb 28, 2017 at 1: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. Commented Feb 28, 2017 at 1:49
  • I got Failed to load resource: net::ERR_INVALID_URL @0019 Commented Feb 28, 2017 at 1:50

5 Answers 5

33

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! :)

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks! But, I dont wan to use <input> tag. I want to read it manualy.
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.
@TrishSiquian you simply can't do it that way, it's browser's security that will prevent you.
@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!!
@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.
|
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);
            }

}

Comments

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.

Comments

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]);           
    });

});

Comments

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.