导出文件
const xhr = new XMLHttpRequest(); const url = ASYNC_URLS.serverUrl + 'rmApi/supp/baseOrderInfo/exportOrderDetailMessage?baseOrderInfo.orderId=' + (this.formInfo.orderId ? this.formInfo.orderId : '') + '&baseOrderInfo.purchaseStatus=' + (this.formInfo.purchaseStatus ? this.formInfo.purchaseStatus : ''); xhr.open('get', url, true); xhr.responseType = 'blob'; let accessToken = sessionStorage.getItem('accessToken'); xhr.setRequestHeader('tokenId', JSON.parse(accessToken).tokenId); xhr.onload = function() { if (this.status === 200) { const blob = this.response; const temp = this.getResponseHeader('Content-disposition').split('=')[1]; // 获取文件名 处理中文乱码 const fileName = decodeURIComponent(temp); if (window.navigator.msSaveOrOpenBlob) { // IE浏览器下 navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } } }; xhr.send(null);
上传文件
uploadHand($event, fileUpload) { const xhr = new XMLHttpRequest(); const files = $event.files; xhr.onreadystatechange = ev => { this.onUpload(ev, files[0].name, fileUpload); }; const url = this.uploadUrl; const formData: FormData = new FormData(); for (let i = 0; i < files.length; i++) { formData.append('file', files[i], files[i].name); } xhr.open('POST', url, true); xhr.setRequestHeader('tokenId', JSON.parse(sessionStorage.getItem('accessToken')).tokenId ); xhr.send(formData); } onUpload(event, fileName, fileUpload) { if (event.target.readyState === 4) { this.fileName = fileName; const res = JSON.parse(event.target.response); if (res['operateSuccess']) { this.tableData = res['baseVendorVos']; this.allowImport = res['allowImport']; this.allowCount = res['allowCount']; this.forbidCount = res['forbidCount']; this.noData = false; this.nextFlag = false; } else { this.noData = true; } } fileUpload.files = []; }
响应头处理
response.setHeader(“Access-Control-Allow-Origin”, “"); response.setHeader(“Access-Control-Expose-Headers”, "”); response.setHeader(“Content-disposition”, “attachment; filename=” + fileName); response.setContentType(“application/vnd.ms-excel;charset=utf-8”); response.setCharacterEncoding(“utf-8”);