0

I have to send a request to my rest API to send an element which contains an image file.

Here is the code calling the request function :

await uploader(async () => {
        let mime = msg.fichier.split(";")[0].split(":")[1];
        let data = atob(msg.fichier.split(",")[1]);
        let bytes = new Uint8Array(data.length);
        for (let i in data) {
          bytes[i] = data.charCodeAt(i);
        }
        let file = new File(
          [bytes],
          msg.data.titre + "." + mime.split("/")[1],
          { type: mime }
        );
        return await upload_fichier(msg.type_fichier, file, { data: msg.data });

Below is the actual graphql request. My goal is to use api Rest request instead of graphql (i know graphql is better but for some reasons i NEED to use api Rest request) :

async function upload_fichier(type, fichier, variables) {
  const body = new FormData();
  variables[type] = null;
  body.append(
    "operations",
    JSON.stringify({
      query:
        `mutation createElement($data: ElementInput!, $${type}: Upload) {
          createElement(data: $data, ${type}: $${type}) {
            element {
              id
            }
          }
        }`.replace(/\s\s+/g, " "),
      variables: variables,
    })
  );
  body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
  body.append("1", fichier);

  const storage = await browser.storage.local.get("refresh_token");
  const headers = {};
  if (storage.refresh_token) {
    headers.authorization = "JWT " + storage.refresh_token;
  }

  const res = await fetch(url_graphql, {
    method: "POST",
    headers: headers,
    body: body,
  });
  return await res.json();

Below is the code i tried to write to do what i want :

async function upload_fichier(type, fichier, variables) {
  const body = new FormData();
  var index = [];
  variables[type] = null;
  // On récupère la valeur de chaque propriété de "variables" 
  for (var variable in variables.data) {
    index.push(variables.data[variable]);
  }
  // Tableau des valeurs de clés
  const keys = Object.getOwnPropertyNames(variables.data);
  var json_str = {};
  for (let i = 0; i < keys.length; i++) {
    json_str[keys[i]] = index[i];
  }
  json_str["options"] = {isnew: true};
  // alert(JSON.stringify(json_str));
  body.append(
    "operations",
    JSON.stringify(json_str)
  );
  body.append("map", JSON.stringify({ "1": [`variables.${type}`] }));
  body.append("1", fichier);
  for (var value of body.values()) {
    alert(value);
  }
  const storage = await browser.storage.local.get("refresh_token");
  const headers = {};
  if (storage.refresh_token) {
    headers.authorization = "JWT " + storage.refresh_token;
  }
  const res = await fetch(url_api + "/elements/", {
    method: "POST",
    headers: headers,
    body: body,
  });

  return await res.json();

But if my element is well sent, it is empty. No title, no description, no image. It seems that body value isn't right. So my Api request is just "url_api/elements/", which just create an empty basic element.

alainebdev
  • 121
  • 1
  • 1
  • 9
  • Do this answer your question https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api ? – Dani May 30 '21 at 09:30
  • I've tried but it didn't worked. Nothing was sent – alainebdev May 30 '21 at 10:27
  • This is what are my formdata values : {"titre":"HISTOIRE LITTÉRAIRE - Moyen Âge : La littérature médiévale - Manuel", "description":"my desc", "credits":"https:/....", "options":{"isnew":true}} {"1":["variables.image »]} [object File] – alainebdev May 30 '21 at 10:59
  • Do you see the data sent to the backend from the dev tools ? maybe it is a problem at the reception in the backend – Dani May 30 '21 at 11:27
  • I've succeeded to post element with title and description but still blocked with miim image file... – alainebdev May 30 '21 at 11:56
  • @Dani Problem is i send request from our chrome extension and so can't inspect request form console... – alainebdev May 30 '21 at 13:05
  • The api rest is made with nodejs ? – Dani May 30 '21 at 13:29
  • @Dani No `code alert(fichier.type); // display "image/png" (without quote) alert(fichier.name); // display "HISTOIRE LITTÉRAIRE - Moyen Âge : La littérature médiévale - Manuel numérique max Belin.png" (without quote) body.append("image", fichier); ` – alainebdev May 30 '21 at 13:35
  • It seem that image property is well described on the request header but for any reason, isn't on preview anymore. Problem appears on 2 request. One for image file so and one for imageurl string... – alainebdev May 31 '21 at 06:33

0 Answers0