weixin_33739646 2016-11-02 10:23 采纳率: 0%
浏览 172

React / Redux下载文件

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 component connected.

The action is asynchronous and does an ajax POST:

export const onXlsxClick = () => dispatch => {
    const urlParams = {
        filters: {
            aggregation: 'macro_area',
            chart_resolution: '1_hour',
            chart_from: '1478080363',
            chart_to: '1477993963'
        },
        labels: ['PROVA1', 'PROVA2'],
        series: [
            {
                label: null,
                timestamp: 1478080363,
                values: [123, 345]
            },
            {
                label: null,
                timestamp: 1477993963,
                values: [153, 3435] 
            }
        ]
    };
    return $.ajax({
        url:'/rest/export/chart/xlsx',
        type: 'POST',
        dataType: 'application/json',
        contentType: 'application/json',
        data: JSON.stringify(urlParams)
    })
    .done(data => {
       console.log('success');
    })
    .fail(error => {
        console.log(error);
    });
};

The server receive the request and handle it correctly through this REST service:

@POST
@Path("xlsx")
@Produces("application/vnd.ms-excel")
public Response getXlsx(ChartExportRequest request) {
    ResponseBuilder responseBuilder;
    ChartExportRequestDTO reqDto = null;
    try {
        reqDto = parseDTO(request);
        checkRequestDTO(reqDto);
        ExportDTO dto = getXlsxProvider().create(reqDto);

        responseBuilder = Response.ok(dto.getFile())
                .header("Content-disposition", "attachment;filename=" + dto.getFileName());
    }
    catch(Exception e) {
        logger.error("Error providing export xlsx for tab RIGEDI with request [" + (reqDto != null ? reqDto.toString() : null) + "]", e);
        responseBuilder = Response.serverError().entity(e.getMessage());
    }
    return responseBuilder.build();
}

The problem is that the response arrives correctly to the client but then nothing happens: I am expecting that the browser shows the download dialog (example: in chrome I expect the bottom bar of downloads to appear with my file).

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • 喵-见缝插针 2017-02-15 09:21
    关注

    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;
    }

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档