import axios from 'axios'; export default function (url, data = {}, method = 'GET', params, headers) { return new Promise((resolve, reject) => { let promise = null; if (method === 'GET') { promise = axios.get(url, {params: data, headers}); } else if (method === 'POST') { promise = axios.post(url, data, {params: params, headers}); } promise .then(response => resolve(response)) .catch(err => { // console.log("/src/axios/ajax.js----error: "+err) reject(err); }); }); }
1. 直接用 Ajax 发 POST/GET 请求
export const requestDownloadLabFile = (id) => { // 下载附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; ajax(url, {}, 'GET', {}, {'labAuth': 'http://localhost:7000'}).then(res=> { const content = res.data; const blob = new Blob([content]); const fileName = 'fileName.type'; if ('download' in document.createElement('a')) { // 非IE下载 const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); } else { // IE10+下载 navigator.msSaveBlob(blob, fileName); } }); return 0; }
form 当前页下载: (当 链接失效 时,影响当前页,)
export const diyDownload = (url, data, method = 'GET') => { const body = document.getElementsByTagName('body')[0]; const form = document.createElement('form'); form.method = method; form.action = url; for (let key in data) { let param = document.createElement('input'); param.type = 'hidden'; param.name = key; param.value = data[key]; form.appendChild(param); } body.appendChild(form); form.submit(); body.removeChild(form); }; export const requestDownloadLabFile = (id) => { // 下载附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; diyDownload(url, {}, 'GET'); };
axios实现利用form表单请求下载
let formData = new FormData() // formData.append(b,'2')//必传俩参数,key和value,多个参数可循环传入 let datas = { id:'22323', name:'jack' } for (let key in datas){ formData.append(key,data[key]) } console.log(formData); axios.post('/url',formData).then()
iframe 标签下载: (当 链接失效 时,不会影响当前页)
export const requestDownloadLabFile = (id) => { // 下载附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; try { let elemIF = document.createElement('iframe'); elemIF.src = url; elemIF.style.display = 'none'; document.body.appendChild(elemIF); } catch (e) { myConsole('下载异常!'); } };