如何通过 Gitee API 上传文件到指定仓库

如何通过 Gitee API 上传文件到指定仓库

首先,进入Gitee官方API文档:https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoContentsPath,找到仓库 --> 新建文件接口 -->点击申请授权

找到接口 https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/20d22f0dfd5247ea86d59101cb17ad24.png)

填写基本信息 access_token,owner,repo,path,content,message,branch 等必要参数信息。

参数 Value
access_token 你自己申请的授权 key
owner 用户名称
repo 项目名称
path 文件名称或者图片名称
content 必须是base64的字符串
message 随便写
branch 分支名称

点击左下方【测试】按钮,查看是否成功

( 如果出现404 或者其他 就是没成功)

下方是测试成功的

代码逻辑

复制代码
<template>
  <view class="container">
    <button @click="chooseMedia">选择图片/视频</button>
    <button @click="uploadToGitee" :disabled="!selectedFiles.length">上传到Gitee</button>
    
    <view class="preview-container">
      <view v-for="(file, index) in selectedFiles" :key="index" class="preview-item">
        <image v-if="file.type === 'image'" :src="file.path" mode="aspectFit" class="preview-image"></image>
        <video v-else-if="file.type === 'video'" :src="file.path" controls class="preview-video"></video>
        <text class="file-name">{{ file.name }}</text>
      </view>
    </view>
    
    <view v-if="uploading" class="upload-status">
      上传中... {{ uploadedCount }}/{{ selectedFiles.length }}
    </view>
    <view v-if="uploadError" class="error-message">
      上传失败: {{ uploadError }}
    </view>
    <view v-if="uploadSuccess" class="success-message">
      上传成功!
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedFiles: [],
      uploading: false,
      uploadedCount: 0,
      uploadError: null,
      uploadSuccess: false,
      // Gitee 配置 - 替换为你的实际信息
      giteeConfig: {
        owner: 'your-gitee-username',
        repo: 'your-repo-name',
        branch: 'master',
        token: 'your-gitee-access-token'
      }
    }
  },
  methods: {
    async chooseMedia() {
      try {
        const res = await uni.chooseMedia({
          count: 9,
          mediaType: ['image', 'video'],
          sourceType: ['album', 'camera'],
          maxDuration: 30,
          camera: 'back'
        })
        
        this.selectedFiles = res.tempFiles.map(file => ({
          path: file.tempFilePath,
          name: this.generateFileName(file.tempFilePath),
          type: file.fileType === 'image' ? 'image' : 'video',
          file: file
        }))
        
        this.uploadError = null
        this.uploadSuccess = false
      } catch (err) {
        uni.showToast({
          title: '选择文件失败',
          icon: 'none'
        })
        console.error(err)
      }
    },
    
    generateFileName(filePath) {
      const ext = filePath.split('.').pop()
      const timestamp = new Date().getTime()
      const random = Math.floor(Math.random() * 10000)
      return `file_${timestamp}_${random}.${ext}`
    },
    
    async uploadToGitee() {
      if (!this.selectedFiles.length) return
      
      this.uploading = true
      this.uploadedCount = 0
      this.uploadError = null
      this.uploadSuccess = false
      
      try {
        for (const file of this.selectedFiles) {
          await this.uploadSingleFile(file)
          this.uploadedCount++
        }
        
        this.uploadSuccess = true
        uni.showToast({
          title: '全部文件上传成功',
          icon: 'success'
        })
      } catch (err) {
        this.uploadError = err.message || '上传失败'
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        console.error(err)
      } finally {
        this.uploading = false
      }
    },
    
    async uploadSingleFile(file) {
      // 1. 读取文件内容
      const fileContent = await this.readFileAsBase64(file.path)
      
      // 2. 准备上传数据
      const uploadData = {
        access_token: this.giteeConfig.token,
        content: fileContent,
        message: `Upload ${file.name}`,
        branch: this.giteeConfig.branch
      }
      
      // 3. 调用 Gitee API 上传文件
      const response = await uni.request({
        url: `https://gitee.com/api/v5/repos/${this.giteeConfig.owner}/${this.giteeConfig.repo}/contents/${file.name}`,
        method: 'POST',
        data: uploadData,
        header: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      })
      
      if (response[1].statusCode !== 201) {
        throw new Error(response[1].data.message || '上传失败')
      }
      
      return response[1].data
    },
    
    readFileAsBase64(filePath) {
      return new Promise((resolve, reject) => {
        plus.io.resolveLocalFileSystemURL(filePath, entry => {
          entry.file(file => {
            const reader = new plus.io.FileReader()
            reader.onloadend = evt => {
              // 移除 data URL 前缀
              const base64 = evt.target.result.split(',')[1]
              resolve(base64)
            }
            reader.onerror = reject
            reader.readAsDataURL(file)
          }, reject)
        }, reject)
      })
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
}

button {
  margin: 10px 0;
  padding: 10px;
  background-color: #007AFF;
  color: white;
  border-radius: 5px;
}

button:disabled {
  background-color: #cccccc;
}

.preview-container {
  margin-top: 20px;
}

.preview-item {
  margin-bottom: 15px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 5px;
}

.preview-image {
  width: 100%;
  height: 200px;
}

.preview-video {
  width: 100%;
  height: 200px;
}

.file-name {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.upload-status, .error-message, .success-message {
  margin-top: 10px;
  padding: 10px;
  border-radius: 5px;
}

.upload-status {
  background-color: #f0f0f0;
}

.error-message {
  background-color: #ffeeee;
  color: #ff0000;
}

.success-message {
  background-color: #eeffee;
  color: #00aa00;
}
</style>
相关推荐
街尾杂货店&5 小时前
css word属性
前端·css
fruge7 小时前
2025前端工程化与性能优化实战指南:从构建到监控的全链路方案
前端·性能优化
2501_9159184111 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
知识分享小能手11 小时前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
MC丶科12 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
2501_9159090613 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
赵庆明老师14 小时前
Uniapp微信小程序开发:EF Core 中级联删除
uni-app
lijun_xiao200915 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端
90后的晨仔15 小时前
Pinia 状态管理原理与实战全解析
前端·vue.js
杰克尼15 小时前
JavaWeb_p165部门管理
java·开发语言·前端