programing

데이터 URL 파일 다운로드

nasanasas 2020. 8. 14. 07:51
반응형

데이터 URL 파일 다운로드


나는 누구나 브라우저에서 액세스 할 수있는 완전한 자바 스크립트 기반의 zip / unzip 유틸리티를 만드는 아이디어를 가지고 놀고 있습니다. zip을 브라우저로 직접 드래그하면 그 안에있는 모든 파일을 다운로드 할 수 있습니다. 개별 파일을 끌어서 새 zip 파일을 만들 수도 있습니다.

나는 그것을 서버 측에서하는 것이 더 낫다는 것을 알고있다. 그러나이 프로젝트는 단지 약간의 재미를위한 것이다.

사용 가능한 다양한 방법을 활용하면 파일을 브라우저로 드래그하는 것이 충분히 쉬울 것입니다. (gmail 스타일)

인코딩 / 디코딩은 괜찮을 것입니다. 나는 as3 zip 라이브러리를 봤기 때문에 괜찮을 것이라고 확신합니다.

내 문제는 마지막에 파일을 다운로드하는 것입니다 ..

window.location = 'data:jpg/image;base64,/9j/4AAQSkZJR....' 

이것은 파이어 폭스에서는 잘 작동하지만 크롬에서는 작동하지 않습니다.

을 사용하여 크롬에서 찾은 이미지로 파일을 임베드 할 수 <img src="data:jpg/image;ba.." />있지만 파일이 반드시 이미지 일 필요는 없습니다. 모든 형식이 될 수 있습니다.

누구든지 다른 해결책이나 어떤 종류의 해결 방법을 생각할 수 있습니까?


아이디어 :

  • <a href="data:...." target="_blank">(테스트되지 않음) 시도

  • 데이터 URL 대신 downloadify 사용 (IE에서도 작동 함)


또한 파일에 제안 된 이름 (기본 '다운로드'대신)을 지정하려는 경우 Chrome, Firefox 및 일부 IE 버전에서 다음을 사용할 수 있습니다.

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

그리고 다음 예제는 그 용도를 보여줍니다.

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");

function download(dataurl, filename) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  a.click();
}

download("data:text/html,HelloWorld!", "helloWorld.txt");

또는:

function download(url, filename) {
fetch(url).then(function(t) {
    return t.blob().then((b)=>{
        var a = document.createElement("a");
        a.href = URL.createObjectURL(b);
        a.setAttribute("download", filename);
        a.click();
    }
    );
});
}

download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,HelloWorld!", "helloWorld.txt");


내 경험을 공유하고 누군가가 Firefox에서 작동하지 않는 다운로드 및 2014에 대한 업데이트 된 답변을 멈출 수 있도록 돕고 싶습니다. 아래 스 니펫은 firefox와 chrome 모두에서 작동하며 파일 이름을 허용합니다.

  // Construct the <a> element
  var link = document.createElement("a");
  link.download = thefilename;
  // Construct the uri
  var uri = 'data:text/csv;charset=utf-8;base64,' + someb64data
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  // Cleanup the DOM
  document.body.removeChild(link);

Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:

function downloadDataUrlFromJavascript(filename, dataUrl) {

    // Construct the 'a' element
    var link = document.createElement("a");
    link.download = filename;
    link.target = "_blank";

    // Construct the URI
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();

    // Cleanup the DOM
    document.body.removeChild(link);
    delete link;
}

Cross-browser solutions found up until now:

downloadify -> Requires Flash

databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.

download.js -> http://danml.com/download.html Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.


There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).

  1. Canvas example with save to file support. Just set your document.location.href to the data URI.
  2. Anchor download example. It uses <a href="your-data-uri" download="filename.txt"> to specify file name.

Combining answers from @owencm and @Chazt3n, this function will allow download of text from IE11, Firefox, and Chrome. (Sorry, I don't have access to Safari or Opera, but please add a comment if you try and it works.)

initiate_user_download = function(file_name, mime_type, text) {
    // Anything but IE works here
    if (undefined === window.navigator.msSaveOrOpenBlob) {
        var e = document.createElement('a');
        var href = 'data:' + mime_type + ';charset=utf-8,' + encodeURIComponent(text);
        e.setAttribute('href', href);
        e.setAttribute('download', file_name);
        document.body.appendChild(e);
        e.click();
        document.body.removeChild(e);
    }
    // IE-specific code
    else {
        var charCodeArr = new Array(text.length);
        for (var i = 0; i < text.length; ++i) {
            var charCode = text.charCodeAt(i);
            charCodeArr[i] = charCode;
        }
        var blob = new Blob([new Uint8Array(charCodeArr)], {type: mime_type});
        window.navigator.msSaveOrOpenBlob(blob, file_name);
    }
}

// Example:
initiate_user_download('data.csv', 'text/csv', 'Sample,Data,Here\n1,2,3\n');

One may also initiate data URL downloads via JavaScript. See https://stackoverflow.com/a/13696029/271577 for such a solution (along with text link examples).


For anyone having issues in IE:

Please upvote the answer here by Yetti: saving canvas locally in IE

dataURItoBlob = function(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");

Your problem essentially boils down to "not all browsers will support this".

You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)

참고URL : https://stackoverflow.com/questions/3916191/download-data-url-file

반응형