
[英]How can I create an URL to make a file downloadable automatically using HTML and PHP?
[英]How can I create a button or link that automatically downloads a file based on a URL?
这是一个网站:下载链接生成器
这是页面源代码中的form
:
<form id="download" class="download_action" method="POST">
<input type="hidden" name="action" value="download_action">
<label for="url">Please enter the URL you would like to save as a file:</label>
<div class="field">
<input id="url" class="text mr-3" name="keyword" type="text">
<input class="submit" title="Save target as" type="submit" value="Save target as">
</div>
<div class="tool-target" style="padding-bottom: 10px;"> </div>
<div id="return"> </div>
<input type="hidden" id="_wpnonce" name="_wpnonce" value="5c9a47c6d6" /><input type="hidden" name="_wp_http_referer" value="/tools/download-link-generator" />
</form>
它似乎是一个服务器端解决方案,但我没有太多关于服务器及其工作方式的信息。 我想知道它是如何工作的。 可以免费构建类似的项目,还是我需要付费托管和服务器以及运行它的丰富知识? 我最终想要的是一个可以强制下载的链接/按钮。
是的,它必须在服务器端完成,因为您需要使用 header 生成请求。
您可以轻松地在本地设置网络服务器,尤其是使用Node.JS 时。
以下是使用 PHP 的方法:
HTML 表格:
<form action="download.php" method="post">
<label for="url">Please enter the URL you would like to save as a file:</label>
<input type="text" name="url">
<button type="submit">Download</button>
</form>
下载.php:
<?php
if(isset($_POST['url'])) {
$url = $_POST['url'];
$file_name = basename($url);
$file_path = $url;
header("Content-Disposition: attachment; filename=".$file_name);
header("Content-Type: application/octet-stream");
header("Content-Length: ".filesize($file_path));
readfile($file_path);
exit;
}
这样,当提交表单时,文本输入的内容将作为 POST 请求的一部分发送到download.php
。 该脚本检查 $_POST 数组是否包含名称为url
的元素。 如果是,它会检索url
字段的值,使用basename
从 URL 中提取文件名,设置标头以触发下载,并使用readfile
输出文件的内容。
以下是使用 Node.JS 的方法:
HTML 表格:
<form action="/download" method="post">
<label for="url">Please enter the URL you would like to save as a file:</label>
<input type="text" name="url">
<button type="submit">Download</button>
</form>
节点.JS
const express = require('express');
const app = express();
const fs = require('fs');
const http = require('http');
app.use(express.urlencoded({ extended: true }));
app.post('/download', (req, res) => {
const url = req.body.url;
const fileName = url.split('/').pop();
const file = fs.createWriteStream(fileName);
http.get(url, response => {
response.pipe(file);
file.on('finish', () => {
file.close();
res.setHeader('Content-Disposition', 'attachment; filename=' + fileName);
res.setHeader('Content-Type', 'application/octet-stream');
res.download(fileName, (err) => {
if (err) {
console.error(err);
} else {
console.log('File downloaded');
}
});
});
});
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.