javascript
// main.js
import Vue from 'vue';
import App from './App.vue';
import { downloadTokenFile } from '@/path/to/your/function'; // 替换为您的函数路径
// 将 downloadTokenFile 添加到 Vue 原型上
Vue.prototype.$downloadTokenFile = downloadTokenFile;
new Vue({
el: '#app',
render: h => h(App),
});
javascript
// ExampleComponent.vue
export default {
methods: {
async downloadFile() {
try {
const params = {
// 下载时的具体参数
id: row.id,
};
await this.$downloadTokenFile('/api/download-url', params);
} catch (error) {
console.error(error);
}
},
},
};
/* Ended by AICoder, pid:3998fad1c627467144b30897c0b61912c4b6e505 */
javascript
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); // 等待1秒后移除表单
}
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 };