Load image and insert into a DIV

Asked

Viewed 7,273 times

2

I have the following layout:

inserir a descrição da imagem aqui

I would like when I click LOAD, open the explorer for me to choose the image and click next to the image, where there is a DIV, as happens on various websites.

Have some plugin for this?

  • only a preview?

  • It can be preview, this is the first time I come across this situation.

3 answers

2


There is no need for any plugin for this style, you can simply use the html input element that would be the following:

<input type=file id=teste>

You would soon have a button to select a file on your computer and could rescue the file path as follows, in javascript:

$('#teste').val();

Soon you can just set the src of its element <img> to the resulting file.

var img = $('#teste').val();
$('#id_sua_img').attr('src', img);

Obs:

This only works if it is local, if you want any user to upload a file from their own computer so that it is loaded into their application, then it would have to be uploaded to the server using php and then just use the upload destination path as src of the image

  • Yes, with the input type=file I can upload the file, but I want to show the image in another div.

  • 1

    You’re using jQuery. jQuery for that. @Paulo, update your answer using $("#sua_img").attr("src", $("#teste").val());

  • @Felipestoker if you do not understand the reply comment.

  • 1

    Perfect, it took me a while to understand, but now I understand.

1

Hello, I use the components of Kendo UI, see their example here, but also has examples in W3schools. See the two that will help you.

1

You can use the class FileReader to read the dataurl of the image and play in the div, which in this example mine, is a tag <img>even

var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};

And the HTML code for that:

<img id="uploadPreview" style="width: 100px; height: 75px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
    };
};

So you will get a preview of your image.

  • 1

    Yes, but it is necessary to note that this way the image will not be loaded to the server, so it will not be "saved" anywhere, a simple F5 on the page will make the image disappear.

  • this, only a preview, because of this, it would be better to have a "save" or "save changes" button as many systems have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.