原生js下载服务器文件要怎么写呢,js需要怎么写,php里面又应该怎么弄,我自学,搞不明白,有没有朋友帮我写个例子,万分感谢。
8条回答 默认 最新
- GISer Liu 2023-02-09 05:14关注
您可以在前端使用Ajax请求下载服务器文件。
JavaScript:
var xhr = new XMLHttpRequest(); xhr.open("GET", "/download-file", true); xhr.responseType = "blob"; xhr.onload = function () { if (this.status === 200) { var blob = new Blob([this.response], {type: "application/octet-stream"}); var link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = "file.txt"; link.click(); } }; xhr.send();
PHP:
<?php if (isset($_GET['download-file'])) { $file = "file.txt"; header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=" . urlencode($file)); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); // This doesn't really matter. $fp = fopen($file, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); // This is essential for large downloads } fclose($fp); }
这个例子可以帮助您理解原理。希望对您有所帮助!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录