【问题标题】:Download blank pdf file from async await response in JS从JS中的异步等待响应下载空白pdf文件
【发布时间】:2018-05-22 11:27:12
【问题描述】:

目前在我点击我的 React 项目中的按钮的情况下,会导致组件调度(Redux)与 async-await 和我等待响应。为了下载文件,我在我的助手中给出了这个响应和一个对我来说是必需的名称,我通过它下载 PDF 文件。但是pdf文件是空的。在 postman 中,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(链接);

又怎么了?

【问题讨论】:

    标签: javascript reactjs download redux async-await


    【解决方案1】:

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

    【讨论】:

    • 嗯。您能否向我展示代码的哪一部分不正确以及它的外观?非常感谢您的回答!
    • 好的。我编辑了我的const blob,但它没有解决问题。在 Mac OS 上我仍然下载空白 pdf :(
    • 您在不止一个地方出于不同目的使用了格式参数。您是否还更正了 URL 构建中格式的使用?由于您没有阅读相应的文档,因此此代码中有很多潜在错误的地方。例如,charCodeAt() 方法返回 utf-16,但您将其截断为 8 位数组缓冲区。您是否使用调试器单步执行了此代码,还是仅在 Postman 中看到了 pdf 文件?
    猜你喜欢
    • 2011-09-03
    • 1970-01-01
    • 2019-06-08
    • 2020-12-03
    • 2020-12-09
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多