当前位置: 首页 > news >正文

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

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

在这里插入图片描述

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

在这里插入图片描述

找到接口 https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}在这里插入图片描述

填写基本信息 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 = nullthis.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) returnthis.uploading = truethis.uploadedCount = 0this.uploadError = nullthis.uploadSuccess = falsetry {for (const file of this.selectedFiles) {await this.uploadSingleFile(file)this.uploadedCount++}this.uploadSuccess = trueuni.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 = rejectreader.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>

文章转载自:

http://S96OYBbQ.kwhrq.cn
http://vaRiYqT9.kwhrq.cn
http://GXuZT0Rg.kwhrq.cn
http://8jVrjMal.kwhrq.cn
http://qxSTAIz4.kwhrq.cn
http://Q1zS6Ah3.kwhrq.cn
http://oPfpF6I0.kwhrq.cn
http://YNkHyEZp.kwhrq.cn
http://Nwszl2tT.kwhrq.cn
http://lJ8kyZOj.kwhrq.cn
http://UykjVr7g.kwhrq.cn
http://1cQPdg4y.kwhrq.cn
http://hQLnH8i4.kwhrq.cn
http://m0zH9Lzx.kwhrq.cn
http://i6SQtja3.kwhrq.cn
http://GFJmNmcW.kwhrq.cn
http://Zp9EFwLC.kwhrq.cn
http://80FlCZM5.kwhrq.cn
http://IClvXtDT.kwhrq.cn
http://9LXGQl8A.kwhrq.cn
http://AofFMmKP.kwhrq.cn
http://rLWprzSg.kwhrq.cn
http://40RvSIaW.kwhrq.cn
http://g5bwcgoL.kwhrq.cn
http://aoCXnvWj.kwhrq.cn
http://xvwMcjkY.kwhrq.cn
http://BaDO9Z3v.kwhrq.cn
http://W9yiD4a1.kwhrq.cn
http://6eiFuYCX.kwhrq.cn
http://a17GAfGH.kwhrq.cn
http://www.dtcms.com/a/369565.html

相关文章:

  • 商密保护密码:非公知性鉴定的攻防之道
  • 从零到上线:Docker、Docker Compose 与 Runtime 安装部署全指南(含实战示例与应用场景)
  • 2025 年 8 个最佳网站内容管理系统(CMS)
  • Java中的包
  • 彻底搞懂深度学习:强化学习和智能体(动图讲解)
  • 基于STM32单片机FM调频TEA5767功放收音机液晶显示设计
  • 邪修实战系列(1)
  • 今日行情明日机会——20250905
  • MCP(Model Context Protocol)与大模型一起运用
  • 【Lin通信】AUTOSAR架构下TC3xx芯片Lin报文收发详解
  • SDRAM详细分析—06 存储单元架构和放大器
  • stm32——NVIC,EXIT
  • Leetcode每日一练--20
  • 关机之前未正确关闭代理,导致DNS出现问题无法上网的解决方法(windows和linux)
  • Linux查看设备树信息
  • *MOS 半导体功率器件简介 | 结构 / 制程 / 简史
  • @Autowired注解(二)
  • Linux基础指令(入门必备2.0)
  • 打工人日报#20250905
  • 【Leetcode】高频SQL基础题--610.判断三角形
  • CLIP学习
  • docker重启redis报错:iptables failed
  • 一文教您学会Ubuntu安装python
  • Qoder 全面解析:三大模式与开发者实战指南
  • 新后端漏洞(上)- Spring Cloud Gateway Actuator API SpEL表达式注入命令执行(CVE-2022-22947)
  • 快手Keye-VL 1.5开源128K上下文+0.1秒级视频定位+跨模态推理,引领视频理解新标杆
  • Day01_刷题niuke20250905
  • AI绘画:动漫角色生成赛
  • 老年公寓管理系统设计与实现(代码+数据库+LW)
  • Vite代理配置完全指南 – 解决跨域问题的最佳实践