import Vue from 'vue';
import App from './App.vue';
import { downloadTokenFile } from '@/path/to/your/function';
Vue.prototype.$downloadTokenFile = downloadTokenFile;
new Vue({
el: '#app',
render: h => h(App),
});
export default {
methods: {
async downloadFile() {
try {
const params = {
id: row.id,
};
await this.$downloadTokenFile('/api/download-url', params);
} catch (error) {
console.error(error);
}
},
},
};
import { getDownloadToken } from '@/api/service';
function createHiddenIframe() {
const iframe = document.createElement('iframe');
iframe.name = 'downLoadframe';
iframe.id = 'hiddenIframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
function downloadFile(url, params = {}, authInfo) {
if (!document.getElementById('hiddenIframe')) {
createHiddenIframe();
}
const iframe = document.getElementById('hiddenIframe');
const form = document.createElement('form');
form.method = 'post';
form.enctype = 'multipart/form-data';
form.style.display = 'none';
for (const key in params) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.action = `${url}?uuid=${authInfo.uuid}&value=${authInfo.value}`;
form.target = 'downLoadframe';
form.submit();
iframe.onload = function () {
const response = JSON.parse(iframe.contentWindow.document.body.innerText);
if (response.code !== 0) {
handleFailure(response.message);
} else {
handleSuccess();
}
};
setTimeout(() => {
document.body.removeChild(form);
}, 1000);
}
async function downloadTokenFile(url, params) {
const uuid = new Date().getTime();
const { data, code } = await getDownloadToken(uuid);
try {
if (code === 0) {
const downloadParams = {
...params,
};
const authInfo = {
value: data,
uuid,
};
downloadFile(url, downloadParams, authInfo);
} else {
handleFailure('获取下载令牌失败');
}
} catch (error) {
console.error(error);
handleFailure('下载文件时发生错误');
}
}
function handleSuccess() {
alert('文件下载成功');
}
function handleFailure(message) {
alert(message);
}
export { downloadTokenFile };