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

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



답변

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> 

( 여기에서 .)


답변

나는 질문을 질문했다 알고 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, …)으로 테스트되었습니다.

답변

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


답변

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)