Yêu cầu thg 1 25, 2022 7:43 SA 142 0 1
  • 142 0 1
+1

react js

Chia sẻ
  • 142 0 1

mọi người ơi cho em hỏi là làm thế nào để download 1 file có chứa nội dung về máy bằng react js ạ . em có api chả về nội dung của cái file đó r ạ . mong mọi người giúp đỡ ạ . em cảm ơn .

1 CÂU TRẢ LỜI


Đã trả lời thg 1 26, 2022 3:03 SA
Đã được chấp nhận
0
function download(url, options = {}) {
    if (!options.method) requestConfig.method = "POST"; //method: 'GET', params: {}, data: {}, fileName: 'download'
    if (!options.data) requestConfig.data = options.data;
    if (!options.fileName) requestConfig.fileName = "download";
    requestConfig.url = url;
    requestConfig.responseType = "blob";
    requestConfig = { ...requestConfig, ...options };
    // console.log("requestConfig", requestConfig);
    return axios(requestConfig)
        .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", options.fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        })
        .catch(e => {
            console.log("error download", e);
        });
}

bạn tham khảo xem nhé, mình dùng axios

Chia sẻ
thg 1 26, 2022 3:54 SA

@tuanminpay b ơi như code này sẽ không download được những file mình tải lên như .rar hay những loại khác

Avatar Ngô Văn Tuấn @tuanminpay
thg 1 26, 2022 9:44 SA

@trungnb download đc hết mà bạn

thg 1 27, 2022 2:38 SA

@tuanminpay thank you b . mk giải quyết được vân đề r 👍👍

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí