Rename a file when downloading

1

I would like to know how I can change the filename in a direct link, such as link so that when the user to download the file name is sent to the user changing the name of the file by taking the name in case of the variable $medias["nome"] putting the format at the end getting $medias["nome"].mp4

Being that my site is in one place and the host of direct links on another server.

    
asked by anonymous 13.08.2015 / 05:54

1 answer

5

Using the download attribute=""

You can use the download attribute in html in a link, for example

<a download="media4.mp4" href="http://meusite.com.br/file/374749482.mp4">Download</a>

If the download is not started by a link, you can create a javascript event:

function download(url, nome) {
    var el = document.createElement("a");
        el.download = nome; //Define o nome
        el.href = url; //Define a url
        el.target = "_blank"; //Força abrir em uma nova janela
        el.className = "hide-link"; //Adiciona uma classe css pra ocultar

    document.body.appendChild(el);

    if (el.fireEvent) {
        el.fireEvent("onclick");//Simula o click pra navegadores com suporte ao fireEvent
    } else {
        //Simula o click
        var evObj = document.createEvent("MouseEvents");
        evObj.initEvent("click", true, false);
        el.dispatchEvent(evObj);
    }

    //Remove o link da página
    setTimeout(function() {
        document.body.removeChild(el);
    }, 100);
}

using:

download("http://meusite.com.br/file/374749482.mp4", "media1.mp4");

css:

.hide-link {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

I did not use display: none (or visibility) because I do not know if it affects the click, and I used -9999px with position: absolute to avoid affecting other elements on the page.

Using .htaccess

If media1.mp4 is the only name you will use and the download is from the static file, you will need .htaccess (maybe use apache).

To "rename" you need the header:

Content-Disposition: attachment; filename=...;

The attachment will force the download and the filename will give the name of the download, then create in the /file folder the .htaccess file and play the following content:

<FilesMatch "\.(?i:mp4)$">
    Header set Content-Disposition "attachment; filename=media1.mp4"
</FilesMatch>

Using php

If the page is generated by PHP, or you need the filename to be dynamic, you will have to use PHP and header , for example:

<?php
$nome    = 'media1.mp4'; //Altere o nome aqui
$arquivo = './file/374749482.mp4'; //Altere o nome aqui

header('Content-Disposition: attachment; filename=' . $nome . ';');
header('Content-Type: video/mp4');
header('Content-Transfer-Encoding: binary');

//É necessário informar o tamanho do arquivo pelo php
header('Content-Length: ' . filesize($arquivo));

$handle = fopen($arquivo, 'rb');

while(false === feof($handle)) {
    echo fgets($handle, 1024);
}

fclose($handle);
    
13.08.2015 / 07:38