Skip to content

Instantly share code, notes, and snippets.

@oviniciusfeitosa
Created October 3, 2019 19:23
Show Gist options
  • Save oviniciusfeitosa/cc0ce2be3815551746707e0294448995 to your computer and use it in GitHub Desktop.
Save oviniciusfeitosa/cc0ce2be3815551746707e0294448995 to your computer and use it in GitHub Desktop.
Download files with AJAX (axios) + laravel + filename

Javascript:

export const getFile = (coArquivo, config = { responseType: 'blob' }) => instance.get(`/upload/${coArquivo}`, config)
  .then((response) => {
    const { headers } = response;
    const dadosFilename = headers['content-disposition'].split('filename=');
    const filename = dadosFilename[1];
  
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
  });

cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
    | to accept any value.
    |
    */

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => ['Content-Disposition'],
    'maxAge' => 0,

];

Controller

class UploadController extends Controller
{

    protected $service;

    public function __construct(UploadService $service)
    {
        $this->service = $service;
        $this->middleware('auth:api');
    }


    public function show($identificador)
    {
        return $this->service->downloadArquivo((int) $identificador);
    }
}
...
public function downloadArquivo($identificador)
    {
        $arquivo = $this->_obterArquivo($identificador);
        if (empty($arquivo)) {
            throw new EParametrosInvalidos("O arquivo solicitado não existe.");
        }
        return Storage::download($arquivo->ds_localizacao, $arquivo->no_arquivo);
    }

References: https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment