简体   繁体   中英

How can I create a button or link that automatically downloads a file based on a URL?

Here's a website: Download link generator

And here's the form in the page source:

<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>

It seems to be a server-side solution, but I don't have much information about servers and how they do it. I wonder how it works exactly. Can similar projects be built for free, or do I need paid hosting and a server plus a vast knowledge of running it? What I finally want is a link/button that will force download.

Yes, it must be done server side as you need to generate a request with a header.
You easily set up a webserver locally, especially with Node.JS .


Here is how you can do it with PHP:

HTML form:

<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>

download.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;
}

This way, when the form is submitted, the contents of the text input will be sent to download.php as part of a POST request. The script checks if the $_POST array contains an element with the name url . If it does, it retrieves the value of the url field, uses basename to extract the file name from the URL, sets the headers to trigger a download, and outputs the contents of the file using readfile .




Here is how you can do it with Node.JS:

HTML form:

<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>

Node.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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM