<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Downlod File</title>
<script>
function downloadBlob(data, filename) {
const responseData = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.href = responseData;
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click() &&
link.remove() &&
window.URL.revokeObjectURL(responseData);
}
function getFileName(str) {
const pattern = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/gm;
return pattern.exec(str)[1].replace(/\'/g, "");
}
function download(url) {
return fetch(url, {
method: "get"
})
.then(function(resp) {
if (resp.ok) {
const filename = getFileName(
resp.headers.get("content-disposition")
);
return {
data: resp.blob(),
filename
};
}
throw new Error("Network response was not OK.");
})
.then(function({ data, filename }) {
downloadBlob(data, filename);
})
.catch(function(e) {
console.log(e);
});
}
</script>
</head>
<body>
<div style="display:flex; justify-content: center;">
<button onClick="download('/download.php')">Download File</button>
</div>
</body>
</html>
Created
February 14, 2019 08:03
-
-
Save r17x/2d46a569abe14022fc0a8637431913bf to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment