React/Redux download file

后端 未结 1 1957
忘掉有多难
忘掉有多难 2021-01-07 01:05

I need to download a file from the server when a button is clicked.

I created a MaterialUI button and on its onclick callback i call an action of the container compo

相关标签:
1条回答
  • 2021-01-07 01:39

    AS per Nate's answer here, the response of Ajax request is not recognised by a browser as a file. It will behave in the same way for all Ajax responses. You need to trigger the download popup manually.

    In my implementation, I used filesaverjs to trigger the download popup, once I have received the API response in reducer.

    Since FileSaver uses blob for saving the file, I am sending the response from server as a blob, converting it into string array buffer and then using it to save my file. This approach was described in

    Please find the sample code below for the reducer : (using reducer for state modification, as per Redux) reducer.js

    let fileSaver = require("file-saver");
    
    
    export default function projectReducer(state = {}, action)
    {
        let project;
        switch (action.type) {
            case  GET_PROJECT_SUCCESS :
                project = Object.assign(action.response.data);
                return project;
            case EXPORT_AND_DOWNLOAD_DATA_SUCCESS :
                let data = s2ab(action.response.data);
                fileSaver.saveAs(new Blob([data], {type: "application/octet-stream"}), "test.xlsx");
                return state;
    
    
        }
        return state;
    
    }
    
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
    }

    0 讨论(0)
提交回复
热议问题