program tip

페이지에서 이동하지 않고 다운로드 창을 여는 가장 쉬운 방법

radiobox 2020. 8. 14. 07:37
반응형

페이지에서 이동하지 않고 다운로드 창을 여는 가장 쉬운 방법


현재 페이지에서 벗어나거나 IE6에서 잘 작동하지 않는 팝업을 열지 않고 다운로드 대화 상자를 여는 가장 좋은 크로스 브라우저 방법은 무엇입니까 (헤더에 content-disposion : attachment를 설정할 수 있다고 가정).


7 년이 지났습니다. IE6에서 작동하는지 모르겠지만 FF 및 Chrome에서 OpenFileDialog가 표시됩니다.

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

이 자바 스크립트는 새 창이나 탭을 열지 않는 것이 좋습니다.

window.location.assign(url);

항상 다운로드 링크에 target = "_ blank"를 추가합니다. 그러면 새 창이 열리지 만 사용자가 저장을 클릭하면 새 창이 닫힙니다.


이것을 HTML 헤드 섹션에 넣고 urlvar를 다운로드 할 파일의 URL로 설정합니다 .

<script type="text/javascript">  
function startDownload()  
{  
     var url='http://server/folder/file.ext';    
     window.open(url, 'Download');  
}  
</script>

그런 다음 본문에 넣으면 5 초 후에 자동으로 다운로드가 시작됩니다.

<script type="text/javascript">  
setTimeout('startDownload()', 5000); //starts download after 5 seconds  
</script> 

( 여기에서 .)


이 질문에서 알 수 있듯이 javascript를 사용하여 파일 다운로드를 시작하는 좋은 방법을 찾고 있습니다. 그러나 이러한 답변은 도움이되지 않았습니다. 그런 다음 몇 가지 xbrowser 테스트를 수행 한 결과 iframe이 모든 최신 브라우저 IE> 8에서 가장 잘 작동 함을 발견했습니다.

downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe"); 
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText"); 
document.body.appendChild(downloadFrame); 

class="screenReaderText" 존재하지만 볼 수없는 콘텐츠의 스타일을 지정하는 클래스입니다.

css :

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

html5boilerplate의 .visuallyHidden과 동일

링크가 끊어지면 iframe 메서드가 파일을 열 수 없다는 빈 페이지로 리디렉션하는 것과는 반대로 아무 작업도하지 않기 때문에 javascript window.open 메서드보다 이것을 선호합니다.

window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();

나는 질문을 질문했다 알고 7 years and 9 months ago있지만 많은 게시 된 솔루션은 사용 예를 들어, 작동하지 않는 <iframe>경우에만 작동 FireFox과 함께 일을하지 않습니다 Chrome.

최상의 솔루션 :

파일 다운로드 팝업을 여는 가장 좋은 솔루션 은 다른 답변에 명시된대로 링크 요소를에 추가 할 필요없이 링크 요소 JavaScript를 사용하는 것입니다.HTMLdocument.body

다음 기능을 사용할 수 있습니다.

function downloadFile(filePath){
    var link=document.createElement('a');
    link.href = filePath;
    link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
    link.click();
}

내 응용 프로그램에서 다음과 같이 사용하고 있습니다.

downloadFile('report/xls/myCustomReport.xlsx');

작동 데모 :

function downloadFile(filePath) {
  var link = document.createElement('a');
  link.href = filePath;
  link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
  link.click();
}

downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");

노트 :

  • link.download브라우저가 새 탭에서 파일을 열지 않고 다운로드 팝업을 실행하도록 속성 을 사용해야합니다 .
  • 이것은 여러 파일 유형 (docx, xlsx, png, pdf, ...)으로 테스트되었습니다.

창 위치를 수정하면 특히 websocket과 같은 지속적인 연결이있는 경우 몇 가지 문제가 발생할 수 있습니다. 그래서 저는 항상 좋은 오래된 iframe 솔루션에 의지합니다.

HTML

<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>

자바 스크립트

function downloadButtonClicked() {
    // Simulate a link click
    var url = 'your_download_url_here';
    var elem = document.createElement('a');
    elem.href = url;
    elem.target = 'hiddenIframe';
    elem.click();
}

링크가 유효한 파일 URL에 대한 것이라면 단순히 window.location.href를 할당하면됩니다.

However, sometimes the link is not valid, and an iFrame is required.

Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:

$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
   $(this).remove();
});

Using HTML5 Blob Object-URL File API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
 */
var saveBlobAsFile = function(fileName, fileContents) {
  if (typeof(Blob) != 'undefined') { // using Blob
    var textFileAsBlob = new Blob([fileContents], {
      type: 'text/plain'
    });
    var downloadLink = document.createElement("a");
    downloadLink.download = fileName;
    if (window.webkitURL != null) {
      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
      downloadLink.onclick = document.body.removeChild(event.target);
      downloadLink.style.display = "none";
      document.body.appendChild(downloadLink);
    }
    downloadLink.click();
  } else {
    var pp = document.createElement('a');
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
    pp.setAttribute('download', fileName);
    pp.onclick = document.body.removeChild(event.target);
    pp.click();
  }
} //saveBlobAsFile

var jsonObject = {
  "name": "John",
  "age": 31,
  "city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";

saveBlobAsFile(fileName, fileContents)


How about:

<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">

This way works on all browsers (i think) and let you put a message like: "If the download doesn't start in five seconds, click here."

If you need it to be with javascript.. well...

document.write('<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">');

Regards


A small/hidden iframe can work for this purpose.

That way you don't have to worry about closing the pop up.


After hours of trying, the function is born :) I had a scenario where I had to display loader in time while the file is preparing for download:

Working in Chrome, Safari and Firefox

function ajaxDownload(url, filename = 'file', method = 'get', data = {}, callbackSuccess = () => {}, callbackFail = () => {}) {
    $.ajax({
        url: url,
        method: 'GET',
        xhrFields: {
            responseType: 'blob'
        },
        success: function (data) {
            // create link element
            let a = document.createElement('a'), 
                url = window.URL.createObjectURL(data);

            // initialize 
            a.href = url;
            a.download = filename;

            // append element to the body, 
            // a must, due to Firefox
            document.body.appendChild(a);

            // trigger download
            a.click();

            // delay a bit deletion of the element
            setTimeout(function(){
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            }, 100);

            // invoke callback if any 
            callbackSuccess(data);
        },
        error: function (err) {
            // invoke fail callback if any
            callbackFail(err)
        }
    });

참고URL : https://stackoverflow.com/questions/1066452/easiest-way-to-open-a-download-window-without-navigating-away-from-the-page

반응형