当前位置:首页 > VUE

vue实现文件分享

2026-01-16 22:08:37VUE

Vue 实现文件分享功能

前端文件上传与展示

使用 Vue 和 Element UI 实现文件上传组件,允许用户选择文件并上传到服务器。

<template>
  <div>
    <el-upload
      action="/api/upload"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :file-list="fileList">
      <el-button type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isLt10M;
    },
    handleSuccess(response, file) {
      this.fileList.push({
        name: file.name,
        url: response.url
      });
    }
  }
}
</script>

后端文件存储

使用 Node.js 和 Express 搭建后端服务,接收前端上传的文件并存储在服务器。

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/api/upload', upload.single('file'), (req, res) => {
  const file = req.file;
  res.json({
    url: `/uploads/${file.filename}`
  });
});

app.use('/uploads', express.static('uploads'));

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

文件分享链接生成

为上传的文件生成可分享的链接,包含文件唯一标识符。

// 在 Vue 组件中添加分享方法
methods: {
  generateShareLink(file) {
    const token = Math.random().toString(36).substring(2);
    this.$http.post('/api/share', {
      fileId: file.url,
      token: token
    }).then(response => {
      const shareLink = `${window.location.origin}/share/${token}`;
      this.$copyText(shareLink).then(() => {
        this.$message.success('分享链接已复制到剪贴板');
      });
    });
  }
}

文件下载实现

为分享的链接创建下载页面,允许用户下载文件。

// 后端添加下载路由
app.get('/share/:token', (req, res) => {
  const token = req.params.token;
  // 查询数据库获取文件信息
  const filePath = path.join(__dirname, 'uploads', filename);
  res.download(filePath);
});

// 前端下载组件
<template>
  <div v-if="file">
    <h3>{{ file.name }}</h3>
    <el-button @click="downloadFile">下载文件</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null
    }
  },
  created() {
    const token = this.$route.params.token;
    this.$http.get(`/api/share/${token}`).then(response => {
      this.file = response.data;
    });
  },
  methods: {
    downloadFile() {
      window.location.href = `/api/download/${this.file.id}`;
    }
  }
}
</script>

安全性与权限控制

实现基本的权限验证,确保只有授权用户可以访问分享的文件。

// 后端添加权限验证中间件
function checkPermission(req, res, next) {
  const token = req.params.token;
  // 验证token有效性
  if (isValidToken(token)) {
    next();
  } else {
    res.status(403).send('无权访问此文件');
  }
}

app.get('/share/:token', checkPermission, (req, res) => {
  // 文件下载逻辑
});

文件有效期设置

为分享链接添加有效期限制,过期后自动失效。

// 在分享时记录过期时间
this.$http.post('/api/share', {
  fileId: file.url,
  token: token,
  expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7天后过期
});

// 后端验证时检查过期时间
function checkPermission(req, res, next) {
  const token = req.params.token;
  const shareRecord = getShareRecord(token);
  if (shareRecord && new Date(shareRecord.expires) > new Date()) {
    next();
  } else {
    res.status(403).send('分享链接已过期');
  }
}

vue实现文件分享

标签: 文件vue
分享给朋友:

相关文章

vue实现滚动中断

vue实现滚动中断

Vue 实现滚动中断的方法 在 Vue 中实现滚动中断通常涉及监听滚动事件,并在特定条件下阻止默认行为或停止滚动。以下是几种常见方法: 监听滚动事件并阻止默认行为 通过 @scroll 或 @wh…

vue实现年历

vue实现年历

Vue 实现年历的方法 使用 Vue 实现年历可以通过组件化开发方式,结合日期计算和动态渲染完成。以下是两种常见的实现方式: 基于原生 Vue 的日历组件 创建 Calendar.vue 组件文件,…

vue 实现长列表

vue 实现长列表

Vue 实现长列表的优化方案 虚拟滚动技术 虚拟滚动是处理长列表的高效方式,仅渲染可视区域内的元素。通过计算滚动位置动态加载和卸载DOM节点,大幅减少内存占用和渲染压力。 <template&…

vue循环数组实现

vue循环数组实现

vue循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现多级弹窗

vue实现多级弹窗

Vue 多级弹窗实现方法 方法一:使用动态组件与递归组件 在 Vue 中可以通过动态组件配合递归组件实现多级弹窗。定义一个基础弹窗组件,通过递归调用自身实现层级嵌套。 基础弹窗组件模板示例:…

vue实现检测数组

vue实现检测数组

Vue 中检测数组变化的方法 Vue 的响应式系统无法直接检测到数组的某些变化,因为 JavaScript 的限制。以下是一些解决方案: 使用 Vue.set 或 this.$set Vue…