前端form表单+ifarme方式实现大文件下载


// 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),
});
// 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 */
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 };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值