diff --git a/src/services/agent.ts b/src/services/agent.ts index 45759e4..cc2b244 100644 --- a/src/services/agent.ts +++ b/src/services/agent.ts @@ -249,23 +249,67 @@ class AgentService { } try { - // Cria um elemento temporário para forçar o download - const link = document.createElement('a'); - link.href = fileUrl; - link.download = fileName; - link.target = '_blank'; - link.rel = 'noopener noreferrer'; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); + console.log('Iniciando download:', { fileUrl, fileName }); - console.log('Download iniciado:', { fileUrl, fileName }); + // Tenta primeiro fazer o download via fetch (funciona se CORS estiver configurado) + try { + const response = await fetch(fileUrl, { + method: 'GET', + mode: 'cors', + cache: 'no-cache', + }); + + if (!response.ok) { + throw new Error(`Erro HTTP: ${response.status}`); + } + + // Converte a resposta em blob + const blob = await response.blob(); + + // Cria uma URL temporária para o blob + const blobUrl = URL.createObjectURL(blob); + + // Cria um elemento temporário para forçar o download + const link = document.createElement('a'); + link.href = blobUrl; + link.download = fileName; + document.body.appendChild(link); + link.click(); + + // Remove o elemento e libera a URL temporária + document.body.removeChild(link); + URL.revokeObjectURL(blobUrl); + + console.log('Download via fetch concluído:', { fileUrl, fileName }); + return; + } catch (fetchError: any) { + console.warn('Erro no download via fetch, tentando método alternativo:', fetchError.message); + + // Se falhar (erro de CORS), usa o método alternativo de abrir em nova aba + // Isso permite que o navegador force o download mesmo com restrições de CORS + const link = document.createElement('a'); + link.href = fileUrl; + link.download = fileName; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + + // Para S3, podemos tentar adicionar parâmetros que forçam o download + const url = new URL(fileUrl); + url.searchParams.set('response-content-disposition', `attachment; filename="${encodeURIComponent(fileName)}"`); + link.href = url.toString(); + + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + console.log('Download via link direto iniciado:', { fileUrl, fileName }); + } } catch (error: any) { console.error('Erro ao fazer download:', error); throw { success: false, - message: error.message || 'Erro ao fazer download do arquivo', + message: error.message || 'Erro ao fazer download do arquivo. Verifique se a URL está acessível.', }; } }