0

I try to send file to my github repo via a html process but I fail with the error 422. I have the feeling than my data is good but... nooooo. I'm beginner in this part and I don't find a way to solve my problem.

In this article : https://levelup.gitconnected.com/how-to-upload-images-to-github-via-javascript-59163b8fff27

the personne write about split data with base64 may be it's a track, but I don't know how to code it in my case. Below my try and fail !!!

// 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();
}

and the error message enter image description here

Knupel
  • 323
  • 2
  • 14
  • If you have a DOM `File`, you will need to use the `FileReader` API's `readAsDataURL` to get the data URL from it, which you can then slice to the bare base64 string as discussed in that article. – AKX May 11 '23 at 20:42

1 Answers1

0

I update the code like your suggestion @AKX but that's the same error is returned error 422

// REACT
import React from "react"
// APP
import Layout from "../../components/struct/layout"


export default function ApiGithubToken() {
  return (
    <div>
      <Layout
        title="API Github token"
        link="true"
      >
      </Layout>
      <p>Sélectionner le fichier à déposer sur Github / Select your file to upload in Github</p>
      <input type="file" name="input" onChange={(event) => load(event)}/>
      <br/>
      <br/>
      <button type="submit">CHARGEZ</button>
    </div>
  )
}

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 = () => {
    <>
        <title>API Github Token</title>
        <meta name="author" content="Knupel" />
        <meta name="description" content="Mon petit laboratoire pour tester mes fonctions react, gatsby, javascript, typescript" />
    </>
}

The good thing, now the file passed feel good I believe

enter image description here

Knupel
  • 323
  • 2
  • 14