Using the download attribute=""
You can use the download attribute in html on 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 didn’t use display: none
(or visibility) because I don’t 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 (acaso 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 folder /file
the file . htaccess 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 file name to be dynamic, you will need 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);
Is php or is it a static file?
– Guilherme Nascimento
In case it would be the file that is saved on the user’s pc.
– Striffer
php when I say is if the page
http://meusite.com.br/file/374749482.mp4
is generated by php– Guilherme Nascimento
Not in the case and a direct URL with directory name file and file with name 374749482.mp4 only that in the case the file is in one place and the site in another.
– Striffer