【问题标题】:How to create File object from cloudinary url in JavaScript如何在 JavaScript 中从 cloudinary url 创建文件对象
【发布时间】:2021-09-01 16:48:48
【问题描述】:

我正在尝试从 URL 创建一个 File 对象。我努力尝试,但没有找到解决此问题的解决方案。有人可以帮我解决这个问题吗?

代码

  let blobImages =
  nextProps &&
  nextProps.input &&
  nextProps.input.value &&
  nextProps.input.value.map((item) => {
    let file = new File([item.url], { type: 'image/png' })
    return file
  })

我正在使用这段代码,但这段代码不起作用,它给了我破坏图像的结果。

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6


    【解决方案1】:

    尝试以下方法:

    HTML:

    <img id="myImage"/>
    

    JAVASCRIPT:

    // Accept an external ArrayBuffer from a service (cloud,external server etc.)
        var request = new XMLHttpRequest();
    
    // For testing lets say this is your URL
    request.open( "GET", "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Circle-icons-computer.svg/512px-Circle-icons-computer.svg.png", true );
    
    // Identify that your response has declared as arraybuffer
    request.responseType = "arraybuffer";
    
    // If you are using DOM object, definitelly you will use blob to create your file object 
    request.onload = function( e ) {
       
        var arrayBufferView = new Uint8Array( this.response );
        var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
      
        // Parse and create your image from url
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL( blob );
        
        // Access your div element, where your photo will be presented.
        // Here instead you can alter the code to download the image as file...
        var img = document.querySelector( "#myImage" );
        img.src = imageUrl;
    };
    
    request.send();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-09
      • 2016-05-15
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多