programing

데이터 URI를 사용할 때 권장 파일 이름을 지정할 수 있는 방법이 있습니까?

bestcode 2022. 9. 22. 00:29
반응형

데이터 URI를 사용할 때 권장 파일 이름을 지정할 수 있는 방법이 있습니까?

예를 들어 링크를 따라가면 다음과 같습니다.

data:application/octet-stream;base64,SGVsbG8=

하이퍼링크 자체에 base64로 저장된 데이터로 구성된 파일을 다운로드하라는 메시지가 브라우저에 표시됩니다.마크업에서 기본 이름을 제안하는 방법이 있나요?없는 경우 JavaScript 솔루션이 있습니까?

하다를 사용하세요.download★★★★

<a download='FileName' href='your_url'>

이 속성은 IE11이 아닌 Chrome, Firefox, Edge, Opera, 데스크톱 Safari 10+, iOS Safari 13+에서 작동합니다.

오늘날 Chrome은 이것을 매우 심플하게 합니다.

function saveContent(fileContents, fileName)
{
    var link = document.createElement('a');
    link.download = fileName;
    link.href = 'data:,' + fileContents;
    link.click();
}

HTML 한정:download★★★★

<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>


Javascript만: 다음 코드로 모든 데이터 URI를 저장할 수 있습니다.

function saveAs(uri, filename) {
  var link = document.createElement('a');
  if (typeof link.download === 'string') {
    link.href = uri;
    link.download = filename;

    //Firefox requires the link to be in the body
    document.body.appendChild(link);
    
    //simulate click
    link.click();

    //remove the link when done
    document.body.removeChild(link);
  } else {
    window.open(uri);
  }
}

var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
saveAs(file, 'logo.gif');

Chrome, FirefoxEdge 13+는 지정된 파일 이름을 사용합니다.

IE11, Edge 12 및 Safari 9(속성을 지원하지 않음)는 기본 이름으로 파일을 다운로드하거나 지원되는 파일 유형(이미지, 비디오, 오디오 파일 등)의 경우 새 탭에 파일을 표시합니다.

RFC 2397에 따르면 없습니다.

또한, 어떤 것도 없는 것으로 보인다.의 속성 <a>★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

단, HTML5는 그 후에 이 Atribute를 도입했습니다.<a> 단, 쓰기 들어 MSIE).

netwerk/protocol/data/nsDataHandler.cpp에서 파이어폭스 소스를 조금 찾아봤습니다.

데이터 핸들러는 내용/유형 및 문자 집합만 해석하고 문자열에 ";base64"가 있는지 확인합니다.

rfc는 파일명을 지정하지 않고 적어도 firefox는 파일명을 처리하지 않습니다.코드는 랜덤 이름과 ".part"를 생성합니다.

파이어폭스 로그도 확인했습니다.

[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0

Mozilla 소스를 보려면 다음 파일을 참조하십시오.

data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp

솔루션 검색은 일단 중단해도 될 것 같습니다.솔루션 검색은 없을 것 같기 때문입니다:)

에서 알 수 에는 html5가 있습니다.downloadfirefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download

다음 Javascript 스니펫은 Chrome에서 링크의 새로운 '다운로드' 속성을 사용하고 클릭을 시뮬레이션하여 작동합니다.

function downloadWithName(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

다음으로 그 사용 예를 제시하겠습니다.

downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")

아니요.

전체 목적은 파일이 아니라 데이터 스트림입니다.데이터 원본은 파일로 처리하는 사용자 에이전트에 대한 지식이 없어야 합니다.그렇지 않아요.

you can add a download attribute to the anchor element.

sample:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>

Using service workers, this is finally possible in the truest sense.

  1. Create a fake URL. For example /saveAs/myPrettyName.jpg
  2. URL 사용 장소<a href, <img src, window.open(url), "실제" URL로 수행할 수 있는 모든 작업을 수행합니다.
  3. Inside the worker, catch the fetch event, and respond with the correct data.

The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.

// In the service worker
self.addEventListener( 'fetch', function(e)
{
    if( e.request.url.startsWith( '/blobUri/' ) )
    {
        // Logic to select correct dataUri, and return it as a Response
        e.respondWith( dataURLAsRequest );
    }
});

Look at this link: http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html

Quote:

마지막에는 ;base64에서도 동작합니다(에서와 같이 문제가 발생하지 않습니다).
(Opera에서는 적어도) 다음과 같습니다.

data:text/plain;charset=utf-8;headers=Content-Disposition%3A%20attachment%3B%20filename%3D%22with%20spaces.txt%22%0D%0AContent-Language%3A%20en;base64,4oiaDQo%3D

Also there is some info in the rest messages of the discussion.

There is a tiny workaround script on Google Code that worked for me:

http://code.google.com/p/download-data-uri/

It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.

This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.

Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.

var exportFileName = "export-" + filename;
$('<a></a>', {
    "download": exportFileName,
    "href": "data:," + JSON.stringify(exportData, null,5),
    "id": "exportDataID"
}).appendTo("body")[0].click().remove();

This one works with Firefox 43.0 (older not tested):

dl.js:

function download() {
  var msg="Hello world!";
  var blob = new File([msg], "hello.bin", {"type": "application/octet-stream"});

  var a = document.createElement("a");
  a.href = URL.createObjectURL(blob);

  window.location.href=a;
}

dl.html

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8"/>
    <title>Test</title>
    <script type="text/javascript" src="dl.js"></script>
</head>

<body>
<button id="create" type="button" onclick="download();">Download</button>
</body>
</html>

If button is clicked it offered a file named hello.bin for download. Trick is to use File instead of Blob.

reference: https://developer.mozilla.org/de/docs/Web/API/File

(This answer has been made deprecated by newer technology, but will be kept here for historical interest.)

It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.

이것은, 다음과 같이 할 수 있습니다. 마이너 주요 사용자 개입링크 생성<a href="data:...">right-click me and select "Save Link As..." and save as "example.txt"</a>말씀드렸듯이, 이것은 고상하지 않습니다만, 전문적인 솔루션이 필요 없는 경우에 유효합니다.

플래시를 사용하여 먼저 클립보드에 이름을 복사함으로써 이 작업을 덜 수 있습니다.물론 플래시나 Java(현재 브라우저 지원이 점점 적어지고 있다고 생각합니다)를 사용할 수 있다면 다른 방법을 찾을 수 있을 것입니다.

<a href=.. download=.. >왼쪽 클릭 및 오른쪽 클릭 -> 링크를 다른 이름으로 저장하기 위해 기능합니다.

<img src=.. download=.. >오른쪽 클릭 - > 이미지 저장에는 기능하지 않습니다.다운로드.잽싸게 움직이다

다 :<a href=.. download=..><img src=..></a>

이 기능은 왼쪽 클릭, 오른쪽 클릭, 링크 저장, 오른쪽 클릭, 오른쪽 클릭, 이미지 저장에 사용할 수 있습니다.

data-uri는 2회(href와 src) 작성해야 하므로 큰 이미지 파일의 경우 javascript를 사용하여 uri를 복사하는 것이 좋습니다.

Chrome/Edge 88로 테스트 완료

var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var sessionId ='\n';
var token = '\n';
var caseId = CaseIDNumber + '\n';
var url = casewebUrl+'\n';
var uri = sessionId + token + caseId + url;//data in file
var fileName = "file.i4cvf";// any file name with any extension
if (isIE)
    {
            var fileData = ['\ufeff' + uri];
            var blobObject = new Blob(fileData);
            window.navigator.msSaveOrOpenBlob(blobObject, fileName);
    }
    else //chrome
    {
        window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
         window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
            fs.root.getFile(fileName, { create: true }, function (fileEntry) { 
                fileEntry.createWriter(function (fileWriter) {
                    var fileData = ['\ufeff' + uri];
                    var blob = new Blob(fileData);
                    fileWriter.addEventListener("writeend", function () {
                        var fileUrl = fileEntry.toURL();
                        var link = document.createElement('a');
                        link.href = fileUrl;
                        link.download = fileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }, false);
                    fileWriter.write(blob);
                }, function () { });
            }, function () { });
         }, function () { });
    }

Chrome과 Fire Fox에서 실제로 이 작업을 수행할 수 있습니다.

다음 URL을 시도하면 사용된 코드가 다운로드됩니다.

data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==

언급URL : https://stackoverflow.com/questions/283956/is-there-any-way-to-specify-a-suggested-filename-when-using-data-uri

반응형