如何从 JavaScript 中的二进制数据创建 File 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18283772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:20:33  来源:igfitidea点击:

How to create a File object from binary data in JavaScript

javascriptjqueryajaxfileapi

提问by David Jones

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 请求接收到的二进制数据,我将如何在 JavaScript 中创建一个 File 对象?

$.ajax({
  url: "http://example.com/image.jpg",
  success: function(data) {
    // Convert binary data to File object
  }
});

回答by David Jones

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).

我终于想通了这一点。为了避免跨站点脚本问题,我在我的服务器上创建了一个代理端点。然后我可以将图像 URL 传递到我的服务器,然后服务器对远程文件执行 GET 请求,将响应转换为 Base64,并将其发送回浏览器。然后浏览器可以将数据转换回二进制并创建一个 Blob(就我而言,它与文件一样好)。

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