从JS

时间:2017-12-08 08:45:47

标签: javascript reactjs download redux async-await

当我点击我的React项目中的按钮时,在我的那一刻,使用async-await运行组件调度(Redux)并且我等待响应。要下载该文件,我会在我的帮助程序中提供此响应和名称,以便我下载PDF文件。但pdf文件为空。在邮递员中,PDF文件不为空,因此后端不能出错。我错在哪里?

我的代码行......

export const request = createAction(DOWNLOAD_PDF);
export const success = createAction(DOWNLOAD_PDF_SUCCESS, ({ response, id }) => {
    fileDownload(response, `return-${id}.pdf`); //My helper
    return { payload: { data: response, id } };
});
export const failure = createAction(DOWNLOAD_PDF_FAIL);

export default ({ id }) => {
    return async dispatch => {
        try {
            dispatch(request());
            const response = await returns.getPdf({ id });
            dispatch(success({ response: response.data, id }));
        } catch (error) {
            dispatch(
                failure({
                    payload: {
                        message: 'Awwww, can not download PDF',
                        stack: error.stack,
                    },
                }),
            );
            errorLogger(error, DOWNLOAD_PDF);
        }
    };
};

当然还有帮手 - >

export default function (data, fileName, format = 'utf-8') {
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        const byteNumbers = new Array(data.length); // save file in IE or edge
        for (let i = 0; i < data.length; i += 1) {
            byteNumbers[i] = data.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: format });
        navigator.msSaveBlob(blob, fileName);
        return;
    }

    let url = `data:application/pdf;charset=${format}`;
    if (format === 'windows-1251') {
        url += `;base64,${btoa(data)}`;
    } else {
        url += `,${encodeURIComponent(data)}`;
    }
    const tempLink = document.createElement('a');
    tempLink.href = url;
    tempLink.setAttribute('download', fileName);
    tempLink.setAttribute('target', '_blank');
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
}

UPD 12/12/17

如果要将此代码插入浏览器控制台,则会下载普通的PDF文件

```

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://', true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization-Domain", "http://");
xhr.setRequestHeader("Authorization-Session", "");
xhr.onload = function(e) {
if (this.status == 200) {

const blob = new Blob([this.response], { type:'application/pdf' });

const link = document.createElement('a');
const url = window.URL.createObjectURL(blob);

link.style = 'display: none';
link.href = url;
link.download = `${name}`;

document.body.appendChild(link);

link.click();

window.URL.revokeObjectURL(url);
document.body.removeChild(link);

}
};

xhr.send();

```

但是,如果我将以下代码插入帮助程序,则再次下载空白PDF。

const blob = new Blob([this.response], { type:'application/pdf' });

const link = document.createElement('a');
const url = window.URL.createObjectURL(blob);

link.style = 'display: none';
link.href = url;
link.download = `${name}`;

document.body.appendChild(link);

link.click();

window.URL.revokeObjectURL(url);

document.body.removeChild(联系);

又怎么了?

1 个答案:

答案 0 :(得分:2)

首先,Blob()构造函数的type选项需要mime类型,而不是字符集编码:https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob