我对HTML有一个基本的概念。我想在我的样本网站创建下载链接,但我不知道如何创建它。我如何制作一个下载文件的链接而不是访问它?


当前回答

我知道我迟到了,但这是我搜索1小时后得到的

 <?php 
      $file = 'file.pdf';

    if (! file) {
        die('file not found'); //Or do something 
    } else {
       if(isset($_GET['file'])){  
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($file); }
    }

    ?>

对于可下载链接,我是这样做的

<a href="index.php?file=file.pdf">Download PDF</a>

其他回答

如果您将文件托管在AWS中,这可能适用于您。代码很容易理解。由于浏览器不支持同源下载链接,解决这个问题的一种方法是将图像URL转换为base64 URL。然后,你就可以正常下载了。

    var canvas = document.createElement("canvas")
    var ctx = canvas.getContext('2d')

    var img = new Image()
    img.src = your_file_url + '?' + new Date().getTime();
    img.setAttribute('crossOrigin', '')

    var array = your_file_url.src.split("/")
    var fileName = array[array.length - 1]

    img.onload = function() {
        canvas.width = img.naturalWidth
        canvas.height = img.naturalHeight
        ctx.drawImage(img,
            0, 0, img.naturalWidth, img.naturalHeight,
            0, 0, canvas.width, canvas.height)

        var dataUrl = canvas.toDataURL("image/png", 1)

        var a = document.createElement('a')
        a.href = dataUrl
        a.download = fileName
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
    }

我知道我迟到了,但这是我搜索1小时后得到的

 <?php 
      $file = 'file.pdf';

    if (! file) {
        die('file not found'); //Or do something 
    } else {
       if(isset($_GET['file'])){  
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($file); }
    }

    ?>

对于可下载链接,我是这样做的

<a href="index.php?file=file.pdf">Download PDF</a>

要链接到该文件,请执行与任何其他页面链接相同的操作:

<a href="...">link text</a>

要强制下载即使它们有嵌入式插件(Windows + QuickTime = ugh),你可以在htaccess / apache2.conf中使用这个:

AddType application/octet-stream EXTENSION

在支持HTML5的现代浏览器中,可以实现以下功能:

<a href="link/to/your/download/file" download>Download link</a>

你也可以用这个:

<a href="link/to/your/download/file" download="filename">Download link</a>

这将允许您更改实际正在下载的文件的名称。

下载属性是HTML5中<a>标签的新属性

<a href="http://www.odin.com/form.pdf" download>下载表单</a> 或 <a href="http://www.odin.com/form.pdf" download="Form">下载表单</a> .

我更喜欢第一个,它在任何扩展方面都是可取的。