【发布时间】: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