文件下载 针对安卓系统

复制代码
<template>
  <div>
    <button @click="handleDownload">下载文件</button>

    <!-- 使用一个Dialog组件来提示用户 -->
    <el-dialog
      title="下载提示"
      :visible.sync="dialogVisible"
      width="80%"
      v-if="isMobile"
    >
      <p>检测到您在移动设备上,请选择下载方式:</p>
      <div style="display: flex; justify-content: space-around; margin-top: 20px;">
        <el-button type="primary" @click="openInBrowser">浏览器直接下载</el-button>
        <el-button type="success" @click="copyLink">复制下载链接</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      fileUrl: 'https://your-domain.com/path/to/your/file.pdf',
      isMobile: false // 通过用户代理判断是否是移动设备
    };
  },
  mounted() {
    // 简单的移动设备检测
    this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  },
  methods: {
    handleDownload() {
      // 如果是移动设备,显示提示对话框
      if (this.isMobile) {
        this.dialogVisible = true;
      } else {
        // 如果是PC,直接用方案二下载
        this.downloadFileDirectly();
      }
    },
    openInBrowser() {
      // 方案一:新窗口打开
      window.open(this.fileUrl, '_blank');
      this.dialogVisible = false;
    },
    copyLink() {
      // 使用现代浏览器 Clipboard API
      navigator.clipboard.writeText(this.fileUrl).then(() => {
        this.$message.success('下载链接已复制到剪贴板,请粘贴到浏览器地址栏中打开。');
      }).catch(err => {
        // 如果Clipboard API不支持,使用古老的document.execCommand方法
        const textArea = document.createElement('textarea');
        textArea.value = this.fileUrl;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        this.$message.success('下载链接已复制,请粘贴到浏览器中打开。');
      });
      this.dialogVisible = false;
    },
    downloadFileDirectly() {
      // 方案二的实现
      const link = document.createElement('a');
      link.href = this.fileUrl;
      link.download = '文件.pdf';
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};
</script>
  1. 服务器配置 :确保你的服务器为文件设置了正确的 MIME 类型(如 .apk 对应 application/vnd.android.package-archive),否则浏览器可能无法正确识别。

  2. 文件路径 :务必使用完整的绝对URL (以 http://https:// 开头),不要使用相对路径。

相关推荐
醉挽清风7833 分钟前
Vue+Djiango基础用法
前端·javascript·vue.js
dreams_dream3 分钟前
vue2动态更改css属性方法大全
前端·css
阿基米东5 分钟前
Caddy:把 HTTPS 变成默认选项的现代 Web 服务器
服务器·前端·https
洞窝技术8 分钟前
从原理到落地:大屏适配适配 + 高并发弹幕的企业级技术手册
前端·css
IT_陈寒12 分钟前
JavaScript性能优化:5个V8引擎隐藏技巧让你的代码提速50%
前端·人工智能·后端
菠菜盼娣20 分钟前
第三方插件 unplugin-icons
前端
敲代码的彭于晏25 分钟前
在迁移中学习 React 18:一份来自 React 17 的升级问题清单
前端·react.js
顾安r31 分钟前
12.17 脚本工具 自动化全局跳转
linux·前端·css·golang·html
踢球的打工仔32 分钟前
jquery的基本使用(2)
前端·javascript·jquery
阿蒙Amon38 分钟前
JavaScript学习笔记:16.模块
javascript·笔记·学习