React: Download Button Works, but Downloaded File Is Empty

I’m new to programming, and I’ve been facing some difficulties creating a download button in my React file. In short, I’ve built an API with Kotlin Spring Boot and tested it with JSON. Now, I’m trying to consume this API with React.

My difficulty is with the download feature. The button downloads the file, but it appears empty. However, when I inspect the element, the file appears in the ‘source console’ (Safari) with all its content, allowing me to save it.

Can you help me clarify why the download button does not show the PDF content? What can I do to solve this?

More information on my GitHub: https://github.com/raysatownsend/Consumindo_Api_React/blob/main/src/pages/Books/index.js

thank you!

Expect a help with my code instruction. It may be wrong.

My code is below:

export default function Books() {

const [books, setBooks] = useState([]);
const [page, setPage] = useState(0);
const [files, setFiles] = useState([]);

const navigate = useNavigate();

const accessToken = localStorage.getItem("accessToken");
const username = localStorage.getItem("username");

const authorization = {
    headers:{
        Authorization: `Bearer ${accessToken}`
    }
};

const contentType = {
    headers: {
        "Content-Type": "application/octet-stream",
        "Content-Type": "application/pdf"
    }
}

const responseType = {
    headers: {
        responseType: 'blob',
    }
}

useEffect(() => {
    fetchMoreBooks();
}, [accessToken])

async function fetchMoreBooks() {
    const response = await api.get(`api/books/v1?page=${page}&size=8&direction=asc`, authorization)
    setBooks([...books, ...response.data._embedded.authorVOList]);
    setPage(page + 1);
}

async function editBook(id) {
    try {
        navigate(`/books/book/new/${id}`);
    } catch (error) {
        alert("Edit book failed, please try again.")
    }
}

async function downloadBook() {
    try {
        const response = await api.get("api/file/v1/downloadFile/PRESSMAN_Engenharia_de_software_Uma_Abor.pdf", authorization, contentType, responseType)
        // Create a Blob object from the response data
        const blob = new Blob([...files, ...response.data], { type: response.headers["Content-Type"] });

        // Create a temporary anchor element
        const downloadLink = document.createElement('a');
        downloadLink.href = window.URL.createObjectURL(blob);
        downloadLink.setAttribute('download', 'PRESSMAN_Engenharia_de_software_Uma_Abor.pdf'); // Set the download attribute with desired filename
        document.body.appendChild(downloadLink);
        // Trigger the download by programmatically clicking the anchor element
        downloadLink.click();

        // Cleanup
        window.URL.revokeObjectURL(downloadLink.href);
    } catch (error) {
        alert("ERROR: Can't download choosen item, please try again.");
    }

}

async function deleteBook(id) {
    try {
        await api.delete(`api/books/v1/${id}`, authorization)
        setBooks(books.filter(book => book.id !== id))
    } catch (error) {
        alert("ERROR: Can't delete choosen item, please try again.")
    }
}

async function logout() {
    try {
        localStorage.clear()
        navigate("/")
    } catch (error) {
        alert("Logout failed, please try again.")
    }
}


return (
    <div className="book-container">
        <header>
            <img src={logoImage} alt="Logo" />
            <span>Bem-Vindo, <strong>{username.toUpperCase()}</strong>!</span>
            <Link className="button" to="book/new/0">Add New Book</Link>
            <button onClick={logout} type="button">
                <FiPower size={18} color='#251FC5'/>
            </button>
        </header>

        <h1>Registered Books</h1>
        <ul>
            {books.map(book => (
                <li key={book.id}>
                <strong>Title:</strong>
                <p>{book.title}</p>
                <strong>Author:</strong>
                <p>{book.author}</p>
                <strong>Price:</strong>
                <p>{Intl.NumberFormat('pt-BR', {style: 'currency', currency: 'BRL'}).format(book.price)}</p>
                <strong>Release Date:</strong>
                <p>{Intl.DateTimeFormat('pt-BR').format(new Date(book.launchDate))}</p>

                <button onClick={() => editBook(book.id)} type="button">
                    <FiEdit size={20} color="#251FC5"/>
                </button>
                <button onClick={() => downloadBook()} type="button">
                    <FiDownload size={20} color="#251FC5"/>
                </button>
                <button onClick={() => deleteBook(book.id)} type="button">
                    <FiTrash2 size={20} color="#251FC5"/>
                </button>
            </li>
            ))}
        </ul>
        <button className="button" onClick={fetchMoreBooks} type="button">Load more</button>
    </div>
);

}

New contributor

Raysa Townsend Carraro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật