本文主要是介绍前端form表单+ifarme方式实现大文件下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
// main.jsimport 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),
});
// ExampleComponent.vueexport 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 */
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);document.body.removeChild(iframe);}, 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 };
这篇关于前端form表单+ifarme方式实现大文件下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!