I have an issue when downloading a file from my server.
Uploading it goes well, but when downloading it, I notice that the file is slightly corruptet. It’s 1 byte larger then when I uploaded it, and it seams to be corrupted.
For example, on my local machine before I upload the file:
$> od -x a.txt
0000000 6554 7473 000a
0000005
$> wc -c a.txt
5 a.txt
Now, after the file is uploaded, I’ve checked with the same commands and I get the exact same output.
However, after i download it back to my local machine, I get the following output:
$> od -x a.txt
0000000 540a 7365 0a74
0000006
$> wc -c a.txt
6 a.txt
As you can see, the content has changed and the filesize has increased.
In this example, the file is a simple text-file that can be opened either way, but when I try it with a pdf for example, I get error codes when trying to opened the downloaded file:
mupdf b.pdf
error: cannot recognize version marker
warning: trying to repair broken xref
warning: repairing PDF document
error: no objects found
mupdf: error: cannot open document
Running this command before uploading it gives me no errors.
Here is the code I use to download files. I’m rather sure that the issue is there somewhere:
public function downloadFile($request, $response, $args)
{
global $em;
$fileId = $args['fileId'];
$fileEntity = $em->getRepository('Entity\UploadedFile')->find($fileId);
$directory = $this->getUploadDirectory();
if (empty($fileEntity)) {
throw new \CustomException('UploadFile with id ' . $fileId . ' not found', 123);
}
$filePath = $fileEntity->getPath();
$file = $directory . '/' . $filePath;
$alias = $fileEntity->getAlias();
$fh = fopen($file, 'rb');
$stream = new \Slim\Http\Stream($fh);
$filesize = filesize($file);
return $response->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Description', 'File Transfer')
->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Disposition', 'attachment; filename="' . $alias . '"')
->withHeader('Content-Transfer-Encoding', 'binary')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->withHeader('Pragma', 'public')
->withHeader('Content-Length', $filesize)
->withBody($stream);
}
Note that I have turned off gzip - it makes no difference.
Anyone has a clue about what’s behind this error? There is always the 1 byte size increase no matter how big the file is!
Thanks in advance!