How do I upload an image using the Parse.com javas

2019-02-25 04:15发布

问题:

I'm using Parse.com to build a javascript app, and I need to upload photos. I have a form which allows users to select the image on their filesystem, but what do I do with it next? I can't find any documentation for this on the Parse site (not for the javascriptSDK, anyway).

Thanks for any help!

回答1:

Here's a quick example on how to upload an image:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

  // ***************************************************
  // NOTE: Replace the following your own keys
  // ***************************************************

  Parse.initialize("YOUR_APPLICATION_ID", "YOUR_CLIENT_ID");

  function saveJobApp(objParseFile)
  {
     var jobApplication = new Parse.Object("JobApplication");
     jobApplication.set("applicantName", "Joe Smith");
     jobApplication.set("profileImg", objParseFile);
     jobApplication.save(null, 
     {
        success: function(gameScore) {
          // Execute any logic that should take place after the object is saved.
          var photo = gameScore.get("profileImg");
          $("#profileImg")[0].src = photo.url();
        },
        error: function(gameScore, error) {
          // Execute any logic that should take place if the save fails.
          // error is a Parse.Error with an error code and description.
          alert('Failed to create new object, with error code: ' + error.description);
        }
     });
  }

  $('#profilePhotoFileUpload').bind("change", function(e) {
         var fileUploadControl = $("#profilePhotoFileUpload")[0];
         var file = fileUploadControl.files[0];
         var name = file.name; //This does *NOT* need to be a unique name
         var parseFile = new Parse.File(name, file);

         parseFile.save().then
         (
           function() 
           {
               saveJobApp(parseFile);
           }, 
           function(error) 
           {
             alert("error");
           }
         );
  }); 

});
</script>

<body>
    <input type="file" id="profilePhotoFileUpload">
    <img id="profileImg"/>
</body>


回答2:

Ok, I found the answer after some more Googling (and after it occurred to me to Google 'file upload' instead of just 'image upload'!). I used this:

http://help.gotiggr.com/documentation/services/examples-connecting-to-mobile-back-ends/parse/file-upload

Thought it might come in handy for someone else!