First post... please be nice....
I am trying to upload and download files to a MySQL database but the files are being returned corrupt and I'm not sure why. I am using homestead as my local development environment. Would this not be an issue once pushed to an actual server? The details of the data transactions are detailed below:
I am using Dropzone.js to upload files to the server. When they arrive I encode them in binary using php's base64_decode() and store them in a BLOB data column in the table:
/**
* Upload contact documents
*/
public function postUpload()
{
$contact_id = $this->request->header('X-CONTACT-ID');
$count = count($_FILES['file']['name']);
// check that the file don't exceed the 20MB max gile size
for($i = 0; $i < $count; $i++)
{
if($_FILES['file']['size'][$i] > 20480000) // 20MB
{
return $this->respondBadRequest(['One or more of the files exceed the 20MB maximum file size.']);
}
}
for($i = 0; $i < $count; $i++)
{
$document = new $this->document;
$document->belongs_to = $contact_id; // contact_id
$document->file_name = $_FILES['file']['name'][$i];
$document->mime_type = $_FILES['file']['type'][$i];
$document->size = $_FILES['file']['size'][$i];
$document->data = base64_encode(file_get_contents($_FILES['file']['tmp_name'][$i]));;
$document->uploaded_by = $this->auth->user()->id;
$document->save();
}
return $this->respondHttpCreated();
}
Then when I download them the files, I decode using php's base64_decode(), set headers and return the file contents:
/**
* Get file
*/
public function getShow($id)
{
$document = $this->document->find($id);
if(!$id)
$this->respondNotFound();
$file_contents = base64_decode($document->data);
return response($file_contents)
->header('Cache-Control', 'no-cache private')
->header('Content-Description', 'File Transfer')
->header('Content-Type', $document->mime_type)
->header('Content-length', strlen($file_contents))
->header('Content-Disposition', 'attachment; filename=' . $document->file_name)
->header('Content-Transfer-Encoding', 'binary');
}
Any idea what I'm doing wrong?