Uploading FormData from Trigger.io Forge to Amazon S3

百般思念 提交于 2019-12-03 20:07:59

You are able to use the jQuery ajax $.ajax function and the FormData JavaScript API to upload an image file from your Trigger.io mobile app directly to Amazon S3 as you have done on the web.

You will need to perform the following steps:

  1. Retrieve your file using the forge.file API.
  2. Call forge.file.base64 to return the base64 value for your file's content.
  3. Create a JavaScript Blob object from the returned base64 value
  4. Append the Blob object to your FormData object
  5. Call your $.ajax function to POST the file to Amazon S3

As an example, once you have retrieved your image file (Step 1), you could use the following uploadImage function to upload your image to Amazon S3:

function uploadImage(file, awsAccessKeyId, policy, signature, bucket) {
    forge.file.base64(file, function (base64String) {
      // Create a Blob from a base64 string
      var byteCharacters = atob(base64String);
      var byteNumbers = new Array(byteCharacters.length);
      for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      var byteArray = new Uint8Array(byteNumbers);
      var blob = new Blob([byteArray.buffer], {type: "image/jpeg"});

      var fd = new FormData();
      fd.append('key', 'test.jpg');
      fd.append('acl', 'public-read');
      fd.append('Content-Type', 'image/jpeg');
      fd.append('AWSAccessKeyId', awsAccessKeyId);
      fd.append('policy', policy);
      fd.append('signature', signature);    
      fd.append("file", blob);

      $.ajax({
        type: 'POST',
        url: 'http://' + bucket + '.s3.amazonaws.com/',
        processData: false,
        contentType: false,
        data: fd,
        success: function(response) {
          alert('Success uploading photo');
        },
        error: function () {
          alert('Problem uploading photo');
        }
     });    
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!