using React js and from a laravel api ,I try to download a pdf file but instead it’s just open it in the same window ,by clicking the button Download cv executing the function related .
pliz can you help me to download the file in browser download box , I have seen some resolutions still but have the same problem ,
here is my code :
import React, { useEffect, useState } from "react";
import { Login } from "./parts/login";
import { UseStateContext } from "../context/ContextProvider";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import FormToAddFile from "./parts/BioParts/formToAddFile";
import AlertNotification from "./parts/AlertNotification";
import axiosClient from "../axios-client";
import DownloadPDF from "./parts/BioParts/DownloadPdf";
export default function Bio(){
const {token,user,showLogin,setShowLogin}=UseStateContext();
const [showFormToAddFile,setShowFormToAddFile]=useState(false); //state to manage showing form to add CV file
const [file,setFile]=useState("");
const handleShowLogin=()=>{
if(showLogin){
setShowLogin(false)
}else{
setShowLogin(true)
}
}
// function for showing form to add a CV file
const handleShowToAddFile=()=>{
if(showFormToAddFile){
setShowFormToAddFile(false)
}else{
setShowFormToAddFile(true)
}
}
//
const ShowHideFormAddFile=(value)=>{ //callback to hide and show form file adding
console.log("showhideform",value)
setShowFormToAddFile(value)
}
const handleDownloadCv=()=>{
axiosClient.get(`/getfiles/${1}`,{
headers:{
'Content-Type': 'application/octet-stream',
}
}).then(({data})=>{
console.log(data.file.image)
if(data.file.image){
setFile(data.file.image)
}
}).catch((err)=>{
console.log(err)
})
}
useEffect(()=>{
handleDownloadCv()
},[])
const downloadFileAtURL=(url)=>{
const fileName = url.split("/").pop();
const aTag=document.createElement("a");
aTag.href=url;
aTag.setAttribute("download",fileName);
document.body.appendChild(aTag);
aTag.click();
aTag.remove();
}
return(
<div className="Bio grid lg:grid-cols-2 lg:gap-6 -z-20 grid-cols-1 ">
{ console.log(file)
}
<div className="left max-sm:grid max-sm:justify-center">
{
token? <div> <div className="flex">
<button onClick={()=>{downloadFileAtURL("https://127.0.0.1:8000/storage/"+file)}} formTarget="_blank" className="flex items-center" id="downloadCv" >Download Cv</button>
<button className="ml-2">See profile</button>
<button className="ml-2 imgIconEdit0">
<label htmlFor="iconinput">
<img onClick={handleShowToAddFile} className="" src="/icon/crayon.png" alt="" />
</label>
</button>
</div>
</div>
:
<>
<button onClick={handleShowLogin} className="md:mx-auto">Connect Now</button>
</>
}
</div>
<div className="right">
{showFormToAddFile && <FormToAddFile ShowHideFormAddFile={ShowHideFormAddFile}/> }
</div>
</div>
)
}
I have tried many times but gives me the same result , thank you for help