原生js下载服务器文件要怎么写呢,js需要怎么写,php里面又应该怎么弄,我自学,搞不明白,有没有朋友帮我写个例子,万分感谢。
8条回答 默认 最新
- GISer Liu 2023-02-09 13: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); }
这个例子可以帮助您理解原理。希望对您有所帮助!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示