Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nicklaw5's avatar

Issue encoding, decoding and downloading blob (base64) data from MySQL database

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?

0 likes
3 replies
jalmeyda1403's avatar

Para descargar archivos de una base de datos Mysql, con un campo tipo blob, donde se encuentra el archivo pdf;

  1. Para mi caso use mejor un campo tipo long blob;
  2. No use base_encode64, ni base_decode64; ya que me regresaban el error de false.
  3. Finalmente copio mi código, basado en lo que haz realizado.
  4. Tener en cuenta los caracteres(#@'/) del nombre del archivo que se va a descargar.

public function descargarPDF($curso_prog_cod=null) { $curso_prog = DB::table('curso_prog') ->join('curso', 'curso_prog.curso_cod', '=', 'curso.curso_cod') ->select('curso_prog.', 'curso.' ) ->where('curso_prog.curso_prog_cod',$curso_prog_cod) ->first(); $file_contents = $curso_prog->curso_pdf; return response($file_contents) ->header('Cache-Control', 'no-cache private') ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') ->header('Content-length', strlen($file_contents)) ->header('Content-Disposition', 'attachment; filename=' . $curso_prog->curso_nombre.'.pdf');
}

1 like
raarts's avatar

Gracias jalmeyda1403. This solved the problem for me.

mkashif8912's avatar

In my case, the issue was resolved by using long BLOB field type

Please or to participate in this conversation.