简体   繁体   中英

How do I find the src value of an image uploaded using fileReader?

I'm building a program that allows the user to choose an image to upload. Once the user chooses one, it triggers the previewFile() function, which uses FileReader to display the image.

Now I'm building a function that will download the same image that the user uploaded (and add some style changes). First, I created a new image element, but now I'm stuck, since I can't figure out how to reference the src value of the original image. Once I do get the src value, I can finish adding the styles, then download the edited image.

Here's what I have so far - can anyone help me out?

HTML:

<input type="file" onchange="previewFile()">
<img src="" alt="Preview File...">

JavaScript:

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

      reader.addEventListener("load", function () {
        preview.src = reader.result;
      }, false);

      if (file) {
        reader.readAsDataURL(file);
      }
    }

And the function I need help with:


function createAndDownload() {
      const editedImage = document.createElement('img');

      /*
      Here's where I need help: I need to figure out how to get the image src 
      from the original image, and set it equal to editedImage.src
      */


//add styles
//download editedImage

}

You assigned it this way:

 const preview = document.querySelector('img'); preview.src = reader.result; 

So you do the same thing to read it back:

const preview = document.querySelector('img');
const something = preview.src;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM