programing

링크가 없는 JavaScript BLOB 파일 이름

itsource 2022. 10. 25. 21:47
반응형

링크가 없는 JavaScript BLOB 파일 이름

JavaScript를 통해 blob 파일을 강제로 다운로드 할 때 어떻게 파일 이름을 설정할 수 있습니까?window.location?

function newFile(data) {
    var json = JSON.stringify(data);
    var blob = new Blob([json], {type: "octet/stream"});
    var url  = window.URL.createObjectURL(blob);
    window.location.assign(url);
}

위의 코드를 실행하면 다음과 같은 페이지 새로 고침 없이 파일이 즉시 다운로드됩니다.

bfe440-8d9c-4883-86c5-d76c50a24a1d

대신 파일 이름을 my-download.json으로 설정합니다.

제가 아는 유일한 방법은 FileSaver.js가 사용하는 트릭입니다.

  1. 숨김 생성<a>태그를 붙입니다.
  2. 설정hrefBLOB의 URL에 속합니다.
  3. 속성을 파일명으로 설정합니다.
  4. 를 클릭합니다.<a>태그를 붙입니다.

다음으로 간단한 예(jsfiddle)를 나타냅니다.

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var json = JSON.stringify(data),
            blob = new Blob([json], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

이 예는 단지 아이디어를 설명하기 위해 작성했습니다.제품 코드에서는 FileSaver.js를 대신 사용합니다.

메모들

  • 오래된 브라우저는 HTML5의 일부이기 때문에 "다운로드" 속성을 지원하지 않습니다.
  • 일부 파일 형식은 브라우저에서 안전하지 않은 것으로 간주되어 다운로드가 실패합니다.JSON 파일을 txt 확장자로 저장하는 것이 좋습니다.

Internet Explorer(어쨌든 최신 버전)를 지원하고 jQuery를 사용하여 코드를 정리할 수 있는 답변에 대해 자세히 설명하겠습니다.

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data !== null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

다음은 바이올린의 입니다.행운을 빈다.

위의 솔루션과 같은 원리입니다.그러나 Firefox 52.0(32비트)에서는 큰 파일(40MB 이상)이 랜덤 위치에서 잘리는 문제가 있었습니다.revoke Object Url() 콜을 다시 스케줄링하면 이 문제가 해결됩니다.

function saveFile(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  }
}

jsfiddle 예시

늦었지만 같은 문제가 있었기 때문에 솔루션을 추가했습니다.

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

이게 제 해결책입니다.제 관점에서 보면,<a>.

function export2json() {
  const data = {
    a: '111',
    b: '222',
    c: '333'
  };
  const a = document.createElement("a");
  a.href = URL.createObjectURL(
    new Blob([JSON.stringify(data, null, 2)], {
      type: "application/json"
    })
  );
  a.setAttribute("download", "data.json");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
<button onclick="export2json()">Export data to json file</button>

saveFileOnUserDevice = function(file){ // content: blob, name: string
        if(navigator.msSaveBlob){ // For ie and Edge
            return navigator.msSaveBlob(file.content, file.name);
        }
        else{
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(file.content);
            link.download = file.name;
            document.body.appendChild(link);
            link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
            link.remove();
            window.URL.revokeObjectURL(link.href);
        }
    }

다운로드 버튼의 작동 예에서는 URL에서 고양이 사진을 "cat.jpg"로 저장합니다.

HTML:

<button onclick="downloadUrl('https://i.imgur.com/AD3MbBi.jpg', 'cat.jpg')">Download</button>

JavaScript:

function downloadUrl(url, filename) {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = function(e) {
    if (this.status == 200) {
      const blob = this.response;
      const a = document.createElement("a");
      document.body.appendChild(a);
      const blobUrl = window.URL.createObjectURL(blob);
      a.href = blobUrl;
      a.download = filename;
      a.click();
      setTimeout(() => {
        window.URL.revokeObjectURL(blobUrl);
        document.body.removeChild(a);
      }, 0);
    }
  };
  xhr.send();
}

window.location.assign은 기능하지 않습니다.다운로드가 정상적으로 이루어지지만 Windows 플랫폼의 CSV 파일 확장자를 사용하지 않고 다운로드 됩니다.다음은 나에게 효과가 있었다.

    var blob = new Blob([csvString], { type: 'text/csv' });
    //window.location.assign(window.URL.createObjectURL(blob));
    var link = window.document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // Construct filename dynamically and set to link.download
    link.download = link.href.split('/').pop() + '.' + extension; 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

이것은 그것을 위한 좋은 쉬운 해결책이다.

function downloadBloob(blob,FileName) {
    var link = document.createElement("a"); // Or maybe get it from the current document
    link.href = blob;
    link.download = FileName;
    link.click();
}

pdf를 다운로드하여window.location는필수가아닙니다.jsPdf 를 다음과 같이 사용할 수 있습니다.

// Create document
const doc = new jsPDF('l', 'px', 'a4');

// [...] Add here the jsPdf doc filling

// Launch the document downloading
doc.output('save', 'filename.pdf');

언급URL : https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link

반응형