const myInit = { method: 'GET', mode: 'same-origin', credentials: 'same-origin', cache: 'default'}; fetch(url, myInit).then(res => { const contentType = res.headers.get("Content-Type"); // 根据返回contentType,处理是json,还是下载文件 if (contentType.toLowerCase() == "application/json;charset=utf-8") { res.json().then(data => { alert(data.success); }); } else if (contentType.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { res.blob().then(blob => { // 创建一个a标签,用于下载 var a = document.createElement('a'); var url = window.URL.createObjectURL(blob); var fileName = '被下载的文件.txt'; a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); });
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。
[聚合文章] fetch将返回值进行对应类型的转换
JavaScript
2017-10-18
12 阅读