Jae Kim
Jae Kim

Reputation: 665

Uploading files (pictures) to parse

I am trying to upload a file (a picture, really) unto parse. And I am using the following html to accomplish that:

<body>
    <form id="uploadPhoto">
        <input type="file" id="profilePhotoFileUpload">
        <input type="submit" id="submitButton"  value="Submit" />
    </form>
</body>

Now, the problem is, when I try to get the value of profilePhotoFileUpload var image = document.getElementById('profilePhotoFileUpload').value;, I get a string of the file path instead of the actual picture. For example, when I do alert(image), I get C:fakepath/twitterLogo.png. But I want the actual image to be in that variable. Anybody know how to accomplish this?

I read whole bunch of other posts regarding this and it involved PHP (I don't know PHP). And I was wondering if I could just bypass the PHP part and directly upload it to Parse... Anyhow, please let me know if you have a solution to this problem!

Upvotes: 0

Views: 105

Answers (1)

Alfredo Delgado
Alfredo Delgado

Reputation: 689

If you want to handle files on the client (i.e. don't upload the file to the server) then you have to access the files property on the element.

Here's a quick working sample using vanilla JS: http://jsbin.com/woboju/edit?js,output

With this code you can click on the upload button and select an image. This triggers a change event on the element -- note: not a traditional form submission. In the event handler, the first file object is taken and asynchronously read. Once the file is successfully loaded -- onload -- then a new image element is created, its src attribute is set to the resulting data URL, and the element is appended to the document.

document.getElementById('profilePhotoFileUpload').addEventListener("change", function() {
  var self = this;
  var file = self.files[0];
  var reader = new FileReader();

  reader.onload = function() {
    var img = document.createElement('img');
    img.src = reader.result;

    self.parentNode.appendChild(img);
  };

  reader.readAsDataURL(file);
}, false);

In your final code, you'll want to add some sanity checks, such as making sure that an image has been selected. You could also add support for multiple images being selected at once.

cf. http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

Upvotes: 1

Related Questions