How to Use Content-Disposition For Force a File to Download to the Hard Drive

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

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

See content-disposition on the wikipedia MIME page.

How to set 'Content-Disposition' and 'Filename' when using FileSystemResource to force a file download file?

@RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET)
@PreAuthorize("@authorizationService.authorizeMethod(#id)")
public HttpEntity<byte[]> doAction(@PathVariable ObjectType obj, @PathVariable Date date, HttpServletResponse response) throws IOException {
ZipFileType zipFile = service.getFile(obj1.getId(), date);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getFileName());

return new HttpEntity<byte[]>(zipFile.getByteArray(), headers);
}

Content-disposition: how does it find a file?

The Content-Disposition: attachment;filename="mysong.mp3" header tells the browser to not try to display the body of the response but to save it in a file; the value "mysong.mp3" is a suggestion for the file name but the browsers usually ask the user about what name to use (and provide "mysong.mp3" as default).

This line of code does not read any file from disk and it does not send any content back to the browser. Your code have to do this. It can read the content from a file or generate it on the fly or produce it by any other means; it's entirely up to you.

For example, if you have the content in a file you can do something like this:

$filepath = '/foo/bar/file.mp3';          // put the correct file path and name here

header('Content-Disposition: attachment;filename="mysong.mp3"');
header('Content-Length: '.filesize($filepath));
readfile($filepath);

The Content-Length header is not required but it is useful for the browser to produce a nice progress bar, estimate the remaining time and know, at the end of the transfer, if the file transferred successfully (when it receives the announced number of bytes) or something went wrong (received less bytes).

xHtml download file to hard drive

If you want to force a download prompt, the simplest way to do it is to use some kind of server-side scripting language to modify the headers so they include Content-Disposition: attachment; filename="file.ext". This is very easy in PHP, but it really depends on what languages/facilities your server has available.

There are things you can do to the server configuration itself to force this as well - how you do it depends on the server you are running.

If you wanted to do it in PHP, here is a short example:

getcss.php (placed in the same directory as the HTML file with the link in it)

<?php

if (!isset($_GET['file']) || !file_exists($_GET['file'])) {
header('HTTP/1.1 404 File Not Found');
exit;
}

header('Content-Type: text/css');
header('Content-Length: '.filesize($_GET['file']));
header('Content-Disposition: attachment; filename="'.basename($_GET['file']).'"');
readfile($_GET['file']);
exit;

?>

Then your link would be:

<a href="getcss.php?file=Stylesheets/custom.css">Download This File</a>

How to use the content-disposition header to set a downloaded UTF-8 filename?

Gotcha! I need to use rawurlencode function!

So the right code is:

<?php
function file_generate_download_link($filename = false, $force = true)
{
$json['tempLink'] = 'https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb';
$url = $json['tempLink'];
if($force)
{
$data['download'] = 'true';
}
if($filename)
{
$data['response-content-disposition'] = ' attachment; filename*=UTF-8\'\''.rawurlencode($filename).'';
}
if(isset($data)) {
$data = http_build_query($data);
$url .= '?' . $data;
}
return $url;

}

echo file_generate_download_link($filename = 'Эльбрус Джанмирзоев - Кавказская любовь.mp3');
?>

How to implement Content-Disposition: attachment?

Example of MP3 Lists:

<a href="download.php?file=testing.mp3">Download MP3</a>
<a href="download.php?file=testing2.mp3">Download MP3</a>

download.php :

<?php

$file = $_GET['file'];

header('Content-type: audio/mpeg');

header('Content-Disposition: attachment; filename="'.$file.'"');

?>

How to force a file to download in PHP

If you want to force a download, you can use something like the following:

<?php
// Fetch the file info.
$filePath = '/path/to/file/on/disk.jpg';

if(file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);

// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);

// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
?>

If you simply link to this script using a normal link the file will be downloaded.

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.



Related Topics



Leave a reply



Submit