DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How to Use IP Geolocation in React
  • In-Depth Guide to Using useMemo() Hook in React
  • Select ChatGPT From SQL? You Bet!
  • NEXT.JS 13: Be Dynamic Without Limits

Trending

  • How To Aim for High GC Throughput
  • No Spark Streaming, No Problem
  • How To Handle Technical Debt in Scrum
  • OneStream Fast Data Extracts APIs
  1. DZone
  2. Data Engineering
  3. Databases
  4. Parse's JavaScript API Now Supports Files

Parse's JavaScript API Now Supports Files

Raymond Camden user avatar by
Raymond Camden
·
Jul. 12, 13 · Interview
Like (0)
Save
Tweet
Share
6.68K Views

Join the DZone community and get the full member experience.

Join For Free

Forgive the somewhat haphazard nature of this blog post. I've got a limited amount of time before I board a plane but I didn't want to wait till the morning to post. Earlier today a reader (Arcayne - sounds like an early 80s X-Man) posted a comment that led me to discover that Parse's JavaScript API now supports Files. This wasn't possible in the past. You can read the details about it here but for folks who want to see complete demo code, keep reading.

The first thing I did was build a complete demo using their example of a file upload. I began by creating a simple HTML file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        
        <input type="file" id="fileUploader">
        <button id="fileUploadBtn">Send</button>

        <script src="js/jquery-2.0.3.min.js"></script>
        <script src="js/parse-1.2.8.min.js"></script>
        <script src="js/app.js"></script>        
    </body>
</html>

Note I've got the Parse library loaded. The HTML just contains a file field and a button. Here's the JavaScript code:

$(document).ready(function() {
   
    var parseAPPID = "x";
    var parseJSID = "x";
    
    //Initialize Parse
    Parse.initialize(parseAPPID,parseJSID);
    
    $("#fileUploadBtn").on("click", function(e) {

        var fileUploadControl = $("#fileUploader")[0];
        if (fileUploadControl.files.length > 0) {
            var file = fileUploadControl.files[0];
            var name = "photo.jpg";
            console.log("here goes nothing...");
            var parseFile = new Parse.File(name, file);
            parseFile.save().then(function() {
                console.log("Woot!");
                console.dir(arguments);
            }, function(error) {
                console.log("Error");
                console.dir(error);
            });
        }

    });
    
});

For the most part this is just what the Parse docs have, but as a complete file, hopefully it is helpful. I can confirm this worked perfectly. In the result object I got a URL to the picture I uploaded. Of course, if I did not pick an image this wouldn't work. You do have access to the file name so in theory line 14 could easily be made dynamic.

Ok, I felt bad. The fix was one line:

var name = file.name;

In the zip I'll be sharing this is corrected. So - that would work in PhoneGap if your mobile client allows for file upload fields. I'm not sure which do. I know iOS lets you capture the camera with one, but I'm not sure if I remember if it lets you select files too. As I said, I'm in a rush.

My real question though was if this could work with PhoneGap. I built a test to see if I could use the Camera API and upload it to Parse. For my first test I decided to just use Base64. That's one of the options in PhoneGap and it works with Parse as well. Turns out this worked super easy as well. I won't bother with the HTML, just the JavaScript, and I'll just focus on the important part.

    $("#takePicBtn").on("click", function(e) {
        e.preventDefault();
        navigator.camera.getPicture(gotPic, failHandler, {quality:50, destinationType:navigator.camera.DestinationType.DATA_URL, sourceType:navigator.camera.PictureSourceType.PHOTOLIBRARY});
               
    });
    
    function gotPic(data) {
        var parseFile = new Parse.File("mypic.jpg", {base64:data});
            parseFile.save().then(function() {
                navigator.notification.alert("Got it!", null);
                console.log("Ok");
                console.log(arguments.toString());
            }, function(error) {
                console.log("Error");
                console.log(error);
            });
        
    }

Again - I assume this is all pretty simple, but if it doesn't make sense, let me know. I specified the photo library as I was testing on the iOS simulator.

Woot. So it works. But - I've heard that using base64 for image data in PhoneGap can be a bit memory intensive. Parse supports a binary array too so I built another demo that made use of "real" files as well. That turned out to be a bit more difficult.

First - PhoneGap can save a camera image to the file system. That part is easy. But the File API is not the most... simple thing to use. The PhoneGap API returns a File URI that you have to turn into a File object that you then have to send to a File Reader. Finally you can get an array buffer object but Parse needs a real array instead. (And for that part I need to thank Si Robertson for his help on G+.)

Here is the code I used. It isn't pretty. But it works.

function gotPic(data) {
        
    window.resolveLocalFileSystemURI(data, function(entry) {

        var reader = new FileReader();
            
        reader.onloadend = function(evt) {
            var byteArray = new Uint8Array(evt.target.result);
            var output = new Array( byteArray.length );
            var i = 0;
            var n = output.length;
            while( i < n ) {
                output[i] = byteArray[i];
                i++;
            }                
            var parseFile = new Parse.File("mypic.jpg", output);

            parseFile.save().then(function(ob) {
                    navigator.notification.alert("Got it!", null);
                    console.log(JSON.stringify(ob));
                }, function(error) {
                    console.log("Error");
                    console.log(error);
                });
                
        }
            
        reader.onerror = function(evt) {
              console.log('read error');
              console.log(JSON.stringify(evt));
          }
            
        entry.file(function(s) {
            reader.readAsArrayBuffer(s);
        }, function(e) {
            console.log('ee');
        });
            
    });
        
}

Anyway - this is very cool and just makes the Parse/PhoneGap combination even cooler. I've attached a copy of my code with my app IDs stripped out. Enjoy!

Download attached file










API JavaScript

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Use IP Geolocation in React
  • In-Depth Guide to Using useMemo() Hook in React
  • Select ChatGPT From SQL? You Bet!
  • NEXT.JS 13: Be Dynamic Without Limits

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: