دریافت فایل از web api و شروع به دانلود سمت کلاینت

آخرین بروز رسانی: 1402/01/08

این روزا که خیلی از سایتها داره با استفاده  از تکنولوژیهای کلاینت سایتی مثل react و vue و angular نوشته میشن و حسابی رو بورس هستن ,قاعدتا  سر و کله زدن با  api به عنوان کد سمت سرور اجتناب ناپذیره


حالا اگر api دارید که مستقیم خروجی فایل میده (مثلن api برای اکسپورت لیست یا ... )
با استفاده از fetch این کد و بنویسید

    const downloadExcel = () => {
        let filter = {
            "startDate": "2020-02-12T05:44:21.105Z",
            "finishDate": "2023-02-12T05:44:21.105Z",
            "columns": [
                {
                    "field": "AccountNumber",
                    "title": "AccountNumber"
                }
            ],
            "exportType": 0
        };

    fetch('https://localhost/api/Export', {
            method: 'POST',
            headers: {
                'Accept': 'application/octet-stream',
                'Content-Type': 'application/json',
                Authorization: 'Bearer --your_auth_token--'
            },
            body: JSON.stringify(filter)
        })
            .then((response) => response.blob())
            .then((myBlob) => {
                const objectURL = URL.createObjectURL(myBlob);
                console.log(myBlob)

                var a = document.createElement('a');
                a.href = objectURL;
                a.download = "filename.xlsx";
                document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
                a.click();

            });
    }

 

اینم همون کد بالاست با استفاده از کتابخانه axios

    const downloadExcel = () => {
        let filter = {
            "startDate": "2020-02-12T05:44:21.105Z",
            "finishDate": "2023-02-12T05:44:21.105Z",
            "columns": [
                {
                    "field": "AccountNumber",
                    "title": "AccountNumber"
                }
            ],
            "exportType": 0
        };

        axios.post("https://localhost/api/Export", filter,
            {
                headers: {
                    'Accept': 'application/octet-stream',
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer --your_auth_token--'
                },
                responseType: 'blob'
            }
        ).then(function (myBlob) {

            const objectURL = URL.createObjectURL(myBlob.data);
            const a = document.createElement('a');
            a.href = objectURL;
            a.download = "filename.xlsx";
            document.body.appendChild(a);
            a.click();

        }
        );
    }

نظر دهید

آدرس ایمیل شما منتشر نخواهد شد. فیلدهای الزامی علامت گذاری شده اند *