Search code examples
phplaravelrestdownload

Wrong Mimetype or Extension when creating a download file API


I am working on a laravel project and make it to serve as a RESTful API.

So I have a feature where user can download files that I store from azure blob storage, the file is in an excel file and sometimes CSV, I have successfully create the download feature, but when I try to open the file it says something like this

The Error message on excel

I use this method to get the MIME types of the file

$mimeType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $file);

And it give me this mime type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' which then I put in the response headers like down below

$headers = [
                'Content-Type' => $mimeType,
                'Content-Description' => 'File Transfer',
                'Content-Disposition' => "attachment; filename=" . $fileName,
                'filename' => $fileName
            ];

But then the problem happens and I try to open the properties of the CORRECT file, it says like this

'Content-type' : 'application/vnd.ms-excel.sheet.macroEnabled.12'

So is there any way to make my response giving the same file that produce no error of extension to the downloaded file?


Solution

  • So I found that the cause of the issue was due to Laravel/Symfony not properly cleaning the output buffer for some reason, you can find the solution down here:

    http://simpledeveloper.com/how-to-fix-laravel-response-image-download-in-laravel/

    Laravel 5 file downloads invalid

    In my case, here is how I implemented it:

    $response = Response::download($path, ...);
    ob_end_clean();
    
    return $response;