답변:
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);
Content-Type: application/octet-stream및 Content-Disposition: attachment.
이 자바 스크립트는 새 창이나 탭을 열지 않는 것이 좋습니다.
window.location.assign(url);
이것을 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브라우저가 새 탭에서 파일을 열지 않고 다운로드 팝업을 실행하도록 속성 을 사용해야합니다 .link클릭하고이 코드를 사용하여, 타임 아웃 후를 숨기기 link.onclick = function() { document.body.innerText = "The file is being downloaded ..."; setTimeout(function() { document.body.innerText = ""; }, 2000); }, 당신은 작업을 볼 수 있습니다 에서 이 fiddle 이지만 권장하는 방법이 아니라는 점을 명심하십시오 Ajax..
이 질문에서 알 수 있듯이 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)
URL.revokeObjectURL(url)메모리를 확보하는 데 파일이 더 이상 필요하지 않을 때 를 호출하는 것도 좋은 방법입니다.
창 위치를 수정하면 특히 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();
}
몇 시간 동안 시도한 후 함수가 탄생했습니다. :) 파일 다운로드를 준비하는 동안 로더를 제때 표시해야하는 시나리오가있었습니다.
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)
}
});
어때 :
<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">');
문안 인사