Magento · December 16, 2015 3

Magento custom options files or images corrupt download

What is happening?

Often store owners need to create custom options at product level to upload files/images, these file upload options appear on product detail page so customers can upload their files.

For example there is a print site, customers pick the business card and want to upload their own design (front and back). For this purpose product is configured at backend with ‘file’ custom options, so customers can upload their own files. Customers choose their own design and upload design with order and checkout.

You as Store owner go to backend to check order detail and try to download custom option files uploaded by customer.
You may experience that the custom options files downloaded are corrupt, these are not opening by any application, but when you try to download them directly using ftp these are ok and opened correctly.

Where is the problem?

When downloading file, Magento calls the _prepareDownloadResponse function defined in the
/app/code/core/Mage/Core/Controller/Front/Action.php file.

Before sending the file contents to output buffer magento does clear the message body but it DOESN’T clear the output buffer, so any thing printed or echoed before download process is also included in the output buffer, as a result when file is downloaded it contains the space or other characters in start and when download it fails to open correctly.

How to fix that?

Fix is very simple. We just need to clear the output buffer before Magento starts sending headers, so you just need to put an ob_clean() function before sending file headers in download process.
Open the following file
/app/code/core/Mage/Core/Controller/Front/Action.php
and in function
_prepareDownloadResponse
Look for the line where it is sending file header i.e
$this->getResponse()->sendHeaders();
and put ob_clean(); right before sending headers.

It should look like this

protected function _prepareDownloadResponse($fileName, $content, $contentType = 'application/octet-stream',
        $contentLength = null
    ) {
    ...
      $this->getResponse()->clearBody();
      ob_clean();
      $this->getResponse()->sendHeaders();
    ...

Save the file and now try to download the file, it will now download correctly.

Wasn’t that awesome?