crie um mock para fazermos um teste deste download
import React, { useState } from "react";
import { useApi } from "../../lib/doctorApi";
import EstiloNovoAtendimento from "../Atendimentos/NovoAtendimento.module.css";
import { AppointmentRequestDTO, Attachment } from "../Atendimentos/types";
import { v4 as uuidv4 } from "uuid";
interface AnexoInterface {
attachments: Attachment[];
setAttachments: (anexos: Attachment[]) => void;
}
const Anexo: React.FC = ({ attachments, setAttachments }) => {
const [loading, setLoading] = useState(false);
const [showPopup, setShowPopup] = useState(false);
const [DownloadPopup, setDownloadPopup] = useState(false);
const [fileToDelete, setFileToDelete] = useState<Attachment | null>(null);
const [fileToDownload, setFileToDownload] = useState<Attachment | null>(null);
const [confirmationInput, setConfirmationInput] = useState("");
const api = useApi();
const [id] = useState(uuidv4());
const handleFileChange = async (
event: React.ChangeEvent
) => {
setLoading(true);
const formData = new FormData();
const files = event.target.files;
if (files) {
Array.from(files).forEach((file) => {
formData.append("files", file);
});
try {
const uploadResult = await api.post("files/upload", formData);
if (
uploadResult.data.success &&
Array.isArray(uploadResult.data.result)
) {
const novosAnexos = [...attachments, ...uploadResult.data.result];
setAttachments(novosAnexos);
}
} catch (error) {
console.error("Erro ao enviar anexos:", error);
}
}
setLoading(false);
};
const initiateDelete = (anexo: Attachment) => {
setFileToDelete(anexo);
setShowPopup(true);
};
const initiateDownload = (anexo: Attachment) => {
setFileToDownload(anexo);
setDownloadPopup(true);
};
const handleDelete = async () => {
if (fileToDelete) {
try {
await api.del(files/delete/${fileToDelete.id});
const novosAnexos = attachments.filter(
(anexo) => anexo.id !== fileToDelete.id
);
setAttachments(novosAnexos);
} catch (error) {
console.error("Erro ao excluir anexo:", error);
} finally {
setShowPopup(false);
setFileToDelete(null);
setConfirmationInput("");
}
}
};
const handleDownload = async () => {
if (fileToDownload) {
console.log("-----------------> teste download", fileToDownload);
try {
// Fazendo um GET para o arquivo
const response = await api.get(files/download/${fileToDownload.id}, {
responseType: "blob", // Define o tipo de resposta como blob
});
console.log("resposta do get sz", response);
// Criar um link temporário para o download
const url = window.URL.createObjectURL(new Blob([response.data]));
// Criar um elemento <a> para fazer o download
const a = document.createElement("a");
a.style.display = "none"; // Não exibe o link
a.href = url;
a.download = fileToDownload.fileName; // Define o nome do arquivo
// Anexa o elemento ao body da página
document.body.appendChild(a);
a.click(); // Dispara o download
// Limpa o URL criado
window.URL.revokeObjectURL(url);
setDownloadPopup(true);
} catch (error) {
console.error("Erro ao baixar o arquivo:", error);
}
}
};
return (
<input
type="file"
multiple
onChange={handleFileChange}
style={{ display: "none" }}
id={fileInput-${id}}
/>
<label
htmlFor={fileInput-${id}}
className={EstiloNovoAtendimento.anexar}
>
Adicionar Novo Anexo
Anexos:
{attachments.length > 0 &&
attachments.map((anexo) => (
{anexo.fileName}
<button
className={EstiloNovoAtendimento.divButton}
onClick={() => initiateDelete(anexo)}
>
Excluir
<button
className={EstiloNovoAtendimento.divButton}
onClick={() => initiateDownload(anexo)} // Ação de download
>
<img src="baixarCinza.png" alt="Baixar" />
<p>Baixar</p>
</button>
</div>
</div>
))}
</div>
</div>
{/* Popup de confirmação */}
{showPopup && (
<>
<div className={EstiloNovoAtendimento.overlay} />
<div className={EstiloNovoAtendimento.popup}>
<strong className={EstiloNovoAtendimento.ArquivoPopup}>
{fileToDelete?.fileName}
</strong>
<p className={EstiloNovoAtendimento.p1}>
Deseja excluir o arquivo?
</p>
<p className={EstiloNovoAtendimento.p2}>
Para confirmar a exclusão
</p>
<p className={EstiloNovoAtendimento.p2}>
permanente deste arquivo, digite
</p>
<strong>"apagar"</strong>
<input
className={EstiloNovoAtendimento.inputExcluir}
type="text"
value={confirmationInput}
onChange={(e) => setConfirmationInput(e.target.value)}
placeholder="'apagar'"
/>
<button
className={`${EstiloNovoAtendimento.buttonExcluir} ${
confirmationInput === "apagar"
? EstiloNovoAtendimento.avaliado
: ""
}`}
onClick={handleDelete}
disabled={confirmationInput !== "apagar"}
>
<div className={EstiloNovoAtendimento.detalhe}>
<p>Excluir</p>
<img src="lixoPng.png" alt="" />
</div>
</button>
<button
className={EstiloNovoAtendimento.buttonCancelar}
onClick={() => setShowPopup(false)}
>
Cancelar
</button>
</div>
</>
)}
{DownloadPopup && (
<>
<div className={EstiloNovoAtendimento.overlay} />
<div className={EstiloNovoAtendimento.popup}>
<strong className={EstiloNovoAtendimento.ArquivoPopup}>
{fileToDownload?.fileName}
</strong>
<p className={EstiloNovoAtendimento.p1}>
Deseja Baixar este arquivo?
</p>
<button
className={EstiloNovoAtendimento.buttonCancelar}
onClick={handleDownload}
>
Baixar Arquivo
</button>
<button
className={EstiloNovoAtendimento.buttonCancelar}
onClick={() => setDownloadPopup(false)}
>
Cancelar
</button>
</div>
</>
)}
</div>
);
};
export default Anexo;