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