简体   繁体   中英

Upload file to Parse (Javascript)

In brief I am trying to store pdf documents into parse. Essentially how it works, a user select the uploaded file from google drive, and from the document selected I want to store into Parse.

I have been able to produce a URL for the pdf document selected from drive, and would like to use that URL to store in Parse.

Below is the code that allows a user to select a pdf document from google drive, and where a unique URL is produced for that item.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>eSnail Scan Upload Part 2</title>

    <script type="text/javascript">

      // The Browser API key obtained from the Google Developers Console.
      var developerKey = 'xxxxxxxxxx';

      // The Client ID obtained from the Google Developers Console.
      var clientId = 'xxxxxxxxxxxxx';

      // Scope to use to access user's photos.
      var scope = ['https://www.googleapis.com/auth/photos'];

      var pickerApiLoaded = false;
      var oauthToken;

      // Use the API Loader script to load google.picker and gapi.auth.
      function onApiLoad() {
        gapi.load('auth', {'callback': onAuthApiLoad});
        gapi.load('picker', {'callback': onPickerApiLoad});
      }

      function onAuthApiLoad() {
        window.gapi.auth.authorize(
            {
              'client_id': clientId,
              'scope': scope,
              'immediate': false
            },
            handleAuthResult);
      }

      function onPickerApiLoad() {
        pickerApiLoaded = true;
        createPicker();
      }

      function handleAuthResult(authResult) {
        if (authResult && !authResult.error) {
          oauthToken = authResult.access_token;
          createPicker();
        }
      }

      // Create and render a Picker object for picking user Photos.
      function createPicker() {
        if (pickerApiLoaded && oauthToken) {
          var picker = new google.picker.PickerBuilder().
              enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
              addView(google.picker.ViewId.PDFS).
              setOAuthToken(oauthToken).
              setDeveloperKey(developerKey).
              setCallback(pickerCallback).
              build();
          picker.setVisible(true);
        }
      }

      // A simple callback implementation.
      function pickerCallback(data) {
        var url = 'nothing';
        if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
          var doc = data[google.picker.Response.DOCUMENTS][0];
          url = doc[google.picker.Document.URL];
        }
        var message = 'The following(s) were stored in Parse: ' + url;
        document.getElementById('result').innerHTML = message;
      }
    </script>
  </head>
  <body>
    <div id="result"></div>

    <!-- The Google API Loader script. -->
    <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
  </body>
</html>

Essentially I have the URL of a file, and would like to store that URL into Parse to be able to retrieve that file later.

Note:

Below is a code I found that allows a user to upload a file into Parse. The problem i do not want the file to come from the user computer (user upload file using file input), but from the URL provided by Google drive.

<HTML>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>

<body>
<form id="fileupload" name="fileupload" enctype="multipart/form-data" method="post">
  <fieldset>
    <input type="file" name="fileselect" id="fileselect"></input>
    <input id="uploadbutton" type="button" value="Upload to Parse"/>
  </fieldset>
</form>

<script type="text/javascript">
  $(function() {
    var file;

    // Set an event listener on the Choose File field.
    $('#fileselect').bind("change", function(e) {
      var files = e.target.files || e.dataTransfer.files;
      // Our file var now holds the selected file
      file = files[0];
    });

    // This function is called when the user clicks on Upload to Parse. It will create the REST API request to upload this image to Parse.
    $('#uploadbutton').click(function() {
      var serverUrl = 'https://api.parse.com/1/files/' + file.name;

      $.ajax({
        type: "POST",
        beforeSend: function(request) {
          request.setRequestHeader("X-Parse-Application-Id", 'pWG7YizRnwxRjplGT9RSLoHtFItDtvmc2EK0YJAe');
          request.setRequestHeader("X-Parse-REST-API-Key", '2LsfIAg5Np9u09ScVIT5StEcO0LXMfpzndWOiwHX');
          request.setRequestHeader("Content-Type", file.type);
        },
        url: serverUrl,
        data: file,
        processData: false,
        contentType: false,
        success: function(data) {
          prompt("File available at: ", data.url);
        },
        error: function(data) {
          var obj = jQuery.parseJSON(data);
          prompt(obj.error);
        }
      });
    });


  });
</script>


</head>
</body>
</HTML>

Any help or suggestion would be greatly appreciated. Thanks in advance.

We had the exact same issue for one of my client's projects. We looked at it a couple of different ways, and decided that the best thing to do was to pass the URL to our own server and handle the upload there. In our specific instance, we used cURL with PHP/Codeignitor, grabbed the file, and then uploaded it to S3 (but the same could easily be done for a Parse upload).

We looked at using CloudCode with a httpRequest, but the problem there is the execution timeout. Parse only gives a short time to each CloudCode function, and the file never would've finished downloading before we got timed-out.

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