RainingChain
RainingChain

Reputation: 7782

JS: Load User Images From Personal Drive

Is there a way to allow the user to look in his personal drive for an image and create a variable in the current webpage out of it? (All this without having to send the image to the server.)

For example, the user select pictures from his drive. He can then move them around in a canvas.

Note: The problem is selecting the image and putting them into variables. I already know how to display them.

Something like <img src="smiley.gif"> will obviously not work.

I am using Jquery.

Upvotes: 0

Views: 41

Answers (1)

Travis Petrie
Travis Petrie

Reputation: 417

I believe what you're looking for would be the Javascript FileReader.readAsDataURL functionality.

You would start by adding some sort of upload/select area that the user could click and bring up their file browser to select some images. After that, you would capture the event and read the file using the fileReader into a data URI, you could then place into an image src attribute, displaying the image. Here's an example from MDN:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>  
</head>
<body>       
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
<script type="text/javascript">
function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
</script>
</body>
</html>

Upvotes: 2

Related Questions