如何创建在JavaScript中的二进制数据的文件对象对象、文件、二进制数、JavaScript

2023-09-10 16:48:07 作者:念卿抚琴

我可能失去了一些东西简单,但我将如何在JavaScript中创建一个File对象给出从AJAX请求接受?二进制数据。

  $。阿贾克斯({
  网址:http://example.com/image.jpg
  成功:功能(数据){
    //转换二进制数据文件对象
  }
});
 

解决方案

我终于想通了这一点。为了避免跨站点脚本问题,我创造了我的服务器上代理端点。然后,我可以通过图片的URL到我的服务器,然后执行远程文件上的GET请求,将响应转换为Base64,并将其发送回浏览器。那么浏览器可以将数据转换为二进制和创建BLOB(这是一样好,我的目的文件)。

  $。阿贾克斯({
  网址:apiRoot +/代理,
  数据:{URL:http://example.com/image.jpg},
  成功:功能(数据){
    变种二进制= ATOB(data.split(,)[1]);
    变种阵列= [];
    对于(VAR I = 0; I< binary.length;我++){
      array.push(binary.char $ C $猫(一));
    }
    var文件=新的斑点([新Uint8Array(阵列),{类型:为image / jpeg'});
  }
});
 

聊一聊 15.5K 的 FileSaver,是如何工作的

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
  }
});

解决方案

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'});
  }
});