7

I'm probably missing something simple here, but how would I create a File object in JavaScript given the binary data as received from an AJAX request?

$.ajax({
  url: "http://example.com/image.jpg",
  success: function(data) {
    // Convert binary data to File object
  }
});
David Jones
  • 10,117
  • 28
  • 91
  • 139
  • this seems relevant: http://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript – Jonah Aug 17 '13 at 00:26

1 Answers1

12

I finally figured this out. In order to avoid cross-site scripting issues, I created a proxy endpoint on my server. Then I can pass the image URL to my server, which then executes a GET request on the remote file, converts the response to Base64, and sends it back to the browser. The browser can then convert the data back to binary and create a Blob (which is as good as a File for my purposes).

$.ajax({
  url: apiRoot + "/proxy",
  data: {url: "http://example.com/image.jpg"},
  success: function(data) {
    var binary = atob(data.split(',')[1]);
    var array = [];
    for (var i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    var file = new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
  }
});
David Jones
  • 10,117
  • 28
  • 91
  • 139
  • 3
    if I used ` var file = new File([new Uint8Array(array)], {type: 'image/jpeg'});` how do I get the name of the image? – jofftiquez Aug 10 '15 at 07:21