如何创建在JavaScript中的二进制数据的文件对象 [英] How to create a File object from binary data in JavaScript

查看:635
本文介绍了如何创建在JavaScript中的二进制数据的文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能失去了一些东西简单,但我将如何在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'});
  }
});
 

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

这篇关于如何创建在JavaScript中的二进制数据的文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆