我嘗試透過 html 進程將檔案傳送到我的 github 儲存庫,但失敗並出現錯誤 422。我感覺我的數據很好,但是......不。我是這部分的初學者,我找不到解決問題的方法。
在這篇文章中: https://levelup.gitconnected.com/how-to-upload-images-to-github-via-javascript-59163b8fff27
有人用 base64
寫了關於分割資料的內容,這可能是一個軌道,但我不知道如何在我的情況下對其進行編碼。以下是我的嘗試和失敗! ! !
// REACT import React from "react" export default function ApiGithubToken() { const load = e => { if(e.target !== null) { let files = e.target.files; if(files.length > 0) { if(files[0] !== null) { const git= { owner : 'knupel', repo: 'gatsby_react_lab', path: `media/test/`, token: process.env.GATSBY_TOKEN_GITHUB, } upload_file(git, files[0]); } } } } return ( <div> <p>Sélectionner le fichier à déposer sur Github / Select your file to upload in Github</p> <input type="file" name="input" onChange={load}/> <br/> <br/> <button type="submit">CHARGEZ</button> </div> ) } const upload_file = async (git: { owner: string; repo: string; path: string; token: string | undefined; }, data: any) => { const res = await fetch(`https://api.github.com/repos/${git.owner}/${git.repo}/contents/${git.path}`, { method: "PUT", headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${git.token}` }, body: JSON.stringify({ message: "Téléversement de votre fichier", content: data // content: data.split('base64,')[1] // content: data.content }) } ); return await res.json(); }
和錯誤訊息
P粉1387117942024-02-26 09:48:21
我按照您的建議@AKX更新了程式碼,但傳回的錯誤是相同的錯誤 422
// REACT import React from "react" // APP import Layout from "../../components/struct/layout" export default function ApiGithubToken() { return () } function load(event:any) { if(event !== undefined && event.target.type === "file") { const file = event.target.files[0]; console.log("file",file); const reader = new FileReader(); if (file) { reader.readAsDataURL(file); } reader.addEventListener("load", () => { const git= { owner : 'knupel', repo: 'gatsby_react_lab', path: `media/test/`, token: process.env.GATSBY_TOKEN_GITHUB, } upload_file(git , reader.result); }, false); } } const upload_file = async (git: { owner: string; repo: string; path: string; token: string | undefined; }, data: any) => { let final_path = `https://api.github.com/repos/${git.owner}/${git.repo}/contents/${git.path}`; console.log("data", data); const res = await fetch(final_path, { method: "PUT", headers: { Accept: "application/vnd.github json", Authorization: `Bearer ${git.token}` }, body: JSON.stringify({ message: "Téléversement de votre fichier", content: data, // content: data.split('base64,')[1] // content: data.content }) } ); return await res.json(); } export const Head = () => { <>Sélectionner le fichier à déposer sur Github / Select your file to upload in Github
load(event)}/>
API Github Token > }
好事,現在文件通過了,我相信感覺很好