developer tip

개체 URL에서 파일 또는 Blob을 가져 오는 방법은 무엇입니까?

copycodes 2020. 8. 15. 09:26
반응형

개체 URL에서 파일 또는 Blob을 가져 오는 방법은 무엇입니까?


사용자가 끌어서 놓기 및 기타 방법을 통해 페이지에 이미지를로드 할 수 있습니다. 이미지가 드롭되면 이미지 URL.createObjectURL를 표시하기 위해 객체 URL로 변환하는 데 사용 합니다. 나는 그것을 재사용하기 때문에 URL을 취소하지 않습니다.

그것은 만들 수있는 시간이 온다 때, FormData나는 그들이 거기에 그 이미지 중 하나를 사용하여 양식을 업로드 할 수 있도록 할 수 있도록 객체를, 내가 다음에 그 개체의 URL 다시 반전 할 수있는 몇 가지 방법이있다 Blob또는 FileA를 다음 APPEND 그것이 내가 할 수 있도록이 FormData목적?


gengkev가 위의 주석에서 언급했듯이이를 수행하는 가장 좋은 / 유일한 방법은 비동기 xhr2 호출을 사용하는 것 같습니다.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//your.blob.url.here', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
    // myBlob is now the blob that the object URL pointed to.
  }
};
xhr.send();

업데이트 (2018) : ES5를 안전하게 사용할 수있는 상황에 대해 Joe는 아래에 더 간단한 ES5 기반 답변이 있습니다.


최신 솔루션 :

let blob = await fetch(url).then(r => r.blob());

URL은 개체 URL 또는 일반 URL 일 수 있습니다.


누군가 React / Node / Axios로 작업 할 때 유용하다고 생각할 수 있습니다. react-dropzoneUI에서 Cloudinary 이미지 업로드 기능에 이것을 사용했습니다 .

    axios({
        method: 'get',
        url: file[0].preview, // blob url eg. blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc
        responseType: 'blob'
    }).then(function(response){
         var reader = new FileReader();
         reader.readAsDataURL(response.data); 
         reader.onloadend = function() {
             var base64data = reader.result;
             self.props.onMainImageDrop(base64data)
         }

    })

BlobBuilder가 Chrome에서 작동하지 않으므로 다음을 사용해야 함을 나타내는 XHR 요청에서 BLOB 데이터 가져 오기를 참조 하세요.

xhr.responseType = 'arraybuffer';

어쨌든 캔버스에 파일을 표시하는 경우 캔버스 콘텐츠를 Blob 개체로 변환 할 수도 있습니다.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

불행히도 @BrianFreud의 대답은 내 요구에 맞지 않고 약간 다른 필요가 있었고 @BrianFreud의 질문에 대한 대답이 아니라는 것을 알고 있지만 많은 사람들이 내 필요로 여기에 왔기 때문에 여기에 남겨 둡니다. 나는 'URL에서 파일이나 blob을 얻는 방법'과 같은 것이 필요했고 현재 정답은 도메인 간이 아니기 때문에 내 요구에 맞지 않습니다.

I have a website that consumes images from an Amazon S3/Azure Storage, and there I store objects named with uniqueidentifiers:

sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf

Some of this images should be download from our system interface. To avoid passing this traffic through my HTTP server, since this objects does not require any security to be accessed (except by domain filtering), I decided to make a direct request on user's browser and use local processing to give the file a real name and extension.

To accomplish that I have used this great article from Henry Algus: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

1. First step: Add binary support to jquery

/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0 
* @author Henry Algus <henryalgus@gmail.com>
*
*/

// use this transport for "binary" data type
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
        return {
            // create new XMLHttpRequest
            send: function (headers, callback) {
                // setup all variables
                var xhr = new XMLHttpRequest(),
        url = options.url,
        type = options.type,
        async = options.async || true,
        // blob or arraybuffer. Default is blob
        dataType = options.responseType || "blob",
        data = options.data || null,
        username = options.username || null,
        password = options.password || null;

                xhr.addEventListener('load', function () {
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

                // setup custom headers
                for (var i in headers) {
                    xhr.setRequestHeader(i, headers[i]);
                }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function () {
                jqXHR.abort();
            }
        };
    }
});

2. Second step: Make a request using this transport type.

function downloadArt(url)
{
    $.ajax(url, {
        dataType: "binary",
        processData: false
    }).done(function (data) {
        // just my logic to name/create files
        var filename = url.substr(url.lastIndexOf('/') + 1) + '.png';
        var blob = new Blob([data], { type: 'image/png' });

        saveAs(blob, filename);
    });
}

Now you can use the Blob created as you want to, in my case I want to save it to disk.

3. Optional: Save file on user's computer using FileSaver

I have used FileSaver.js to save to disk the downloaded file, if you need to accomplish that, please use this javascript library:

https://github.com/eligrey/FileSaver.js/

I expect this to help others with more specific needs.


Using fetch for example like below:

 fetch(<"yoururl">, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + <your access token if need>
    },
       })
.then((response) => response.blob())
.then((blob) => {
// 2. Create blob link to download
 const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `sample.xlsx`);
 // 3. Append to html page
 document.body.appendChild(link);
 // 4. Force download
 link.click();
 // 5. Clean up and remove the link
 link.parentNode.removeChild(link);
})

You can paste in on Chrome console to test. the file with download with 'sample.xlsx' Hope it can help!

참고URL : https://stackoverflow.com/questions/11876175/how-to-get-a-file-or-blob-from-an-object-url

반응형