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


118

현재 페이지에서 벗어나거나 Internet Explorer (IE ) 6.

답변:


106

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);

먼저이 솔루션에 감사드립니다.하지만 removeChild (a) zip이 zip 오류로 압축 해제되면 버그를 발견했습니다. 따라서이 코드를 제거하여 해결하십시오
Roy

2
@Manoj Rana-FF 58.0.2 (64 비트)에서 작동하는지 확인했습니다. 두 줄을 제거하면 어떤 FF에서도 작동하지 않습니다 . document.body.appendChild (a); document.body.removeChild (a);
0x000f

1
Edge 16에서 작동하려면 파일이있는 헤더에 Content-Type: application/octet-streamContent-Disposition: attachment.
Simon

12
더 이상 작동하지 않습니다. developers.google.com/web/updates/2018/02/…
Paulius Dragunas

2
@ user1933131 크롬은 교차 출처에 대해서만 제거
Brandy23

201

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

window.location.assign(url);

17
window.location = url과 동일합니다. "새 값이 위치 객체에 할당 될 때마다 window.location.assign ()이 수정 된 URL로 호출 된 것처럼 URL을 사용하여 문서가로드됩니다."- developer.mozilla.org/en-US/docs/ Web / API / window.location
Rob Juurlink

13
이로 인해 WebSocket 연결이 끊어집니다.
igorpavlov

4
동일한 솔루션을 사용했지만 다운로드 대화 상자를 여는 대신 동일한 탭에서 파일을 엽니 다.
Techno Cracker

2
URL이 다운로드 페이지 인 경우 window.open (url, '_self')과 동일합니다.
전문가는

5
IE11을 사용할 때 이로 인해 JS가 중지되는 것을 발견했습니다. 그래서 IE 11의 경우 다른 탭을 열었던 window.open (url, '_blank')을 사용했지만 파일이 다운로드되었을 때 해당 탭이 닫혔습니다. 이것은 JS를 계속 실행했습니다.
누가 복음

23

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


2
이것이 최고의 답변입니다. Internet Explorer에서 다운로드 할 링크에 'target = "_ blank"'를 추가하면 브라우저가 다른 곳으로 이동하지 못해 ( "HTML1300 : 탐색이 발생했습니다"가 인쇄 됨) 페이지가 일관되지 않은 상태로 남을 수 있습니다.
user64141

23

이것을 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> 

( 여기에서 .)


2
IE6에서는 사용자가 "저장"을 클릭하면 파일이 저장되지만 팝업은 계속 열려 있기 때문에 작동하지 않습니다. 이것은 허용되지 않습니다.
mkoryak

이 코드는 사파리에서 작동하지 않습니다. 사파리에서 해결하도록 도와주세요.
Renish Khunt 2015

17

나는 질문을 질문했다 알고 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');

작동 데모 :

노트 :

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

파일이 다운로드 될 때까지 로딩 gif를 표시하는 가장 좋은 방법은 무엇입니까?
Ctrl_Alt_Defeat

1
@Ctrl_Alt_Defeat 그런데이 경우는 다운로드 과정을 추적하기 쉽지 않을 것이다, 그러나 하나의 트릭에이 GIF 애니메이션 표시 할 수 있습니다 link클릭하고이 코드를 사용하여, 타임 아웃 후를 숨기기 link.onclick = function() { document.body.innerText = "The file is being downloaded ..."; setTimeout(function() { document.body.innerText = ""; }, 2000); }, 당신은 작업을 볼 수 있습니다 에서 이 fiddle 이지만 권장하는 방법이 아니라는 점을 명심하십시오 Ajax..
cнŝdk

1
firefox에서는 작동하지 않습니다. Firefox에서 다운로드하는 방법?
Manoj Rana

@ManojRana firefox의 경우 this answeriframe 참조를 사용할 수 있습니다 .
cнŝdk

2
이 솔루션은 나를 위해 Chrome, Safari 및 Firefox에서 작동합니다. :)
ariebear

15

이 질문에서 알 수 있듯이 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();

6

HTML5 Blob Object-URL File API 사용 :

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see /programming/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 /programming/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)


2
이것이 최선의 방법이라고 생각합니다 !!
Kushal MK

1
URL.revokeObjectURL(url)메모리를 확보하는 데 파일이 더 이상 필요하지 않을 때 를 호출하는 것도 좋은 방법입니다.
SleepWalker

5

창 위치를 수정하면 특히 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();
}

5

링크가 유효한 파일 URL 인 경우 window.location.href를 할당하기 만하면됩니다.

그러나 때때로 링크가 유효하지 않으며 iFrame이 필요합니다.

창이 열리지 않도록 일반 event.preventDefault를 수행하고 jQuery를 사용하는 경우 다음과 같이 작동합니다.

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

2

몇 시간 동안 시도한 후 함수가 탄생했습니다. :) 파일 다운로드를 준비하는 동안 로더를 제때 표시해야하는 시나리오가있었습니다.

Chrome, Safari 및 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)
        }
    });

0

어때 :

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

이 방법은 모든 브라우저에서 작동하며 (제 생각에) "다운로드가 5 초 내에 시작되지 않으면 여기를 클릭하십시오."와 같은 메시지를 넣을 수 있습니다.

자바 스크립트와 함께 있어야한다면 .. 음 ...

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

문안 인사


0

작은 / 숨겨진 iframe이 이러한 목적으로 작동 할 수 있습니다.

이렇게하면 팝업을 닫는 것에 대해 걱정할 필요가 없습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.