How to update a picture?

System Information
  • **Strapi Version3.6.8:
  • Operating System:
  • **Databasesqlite:
  • **Node Version14:
  • **NPM Version6.14.14:
  • Yarn Version:

Hello,

How could I update a pic with Upload ? My code below work for a new entrie but with an update the new picture is not replaced.

Thank you

function envoiDatas(submitevent) {
    submitevent.preventDefault(); //empeche de rafraichr la page
    const title = formcrud.title.value.trim();
    const category = formcrud.category.value;
    const content = formcrud.content.value; 
    const ispublished = true;   // /!\ dans ce cas ispublished est toujiours off la on le met on pour afficher l'ajout directement
    const picture = fileImage;
    console.log(title,category,content,picture);

    const getuser = getWithExpiry("user");
    const token = JSON.parse(getuser).jwt; //voir fonction connexion

    //Uncaught TypeError: Assignment to constant variable car j'avais mis const au lieu de let
    let fetchstring = "";
    let methodstring = "";
    const idelement = localStorage.getItem("edit");
	if (!idelement) {// if the idelement doesn't exist, return null
		fetchstring = url+"/"+collection;
        methodstring = 'POST';
	} else {
		fetchstring = url+"/"+collection+"/"+idelement;
        methodstring = 'PUT';
    }

    const payload = { //on envoie ces infos sauf l'image
        title,
        content,
        category,
        ispublished
    };

    fetch(fetchstring,{
        method: methodstring,
        headers: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
    })
    .then((response) => response.json())
    .then((envoiData) => { 
      //console.log("ad content data",envoiData);
      const formData = new FormData();
      formData.append("files",picture);
      /*cette image sera associé a un objet de cette collection classifiedad
      sans le s voir strapi -> plugins -> Content-Types Builder*/
      formData.append("ref",collection);
      formData.append("refId",envoiData.id);// quel est l'id
      formData.append("field","picture");//quel est le champ

      //envoi de l'image avec l'id précedent
      fetch(`${url}/upload`,{
        method: 'POST',
        body: formData
      })
      .then((response) => {
          console.log("res image upload",response);
          hideForm();
          init();
      })
    })
    .catch(err => {
        console.error(err);
    })
}

2 Likes

Hi I am having the same exact problem.
Were you able to solve this?
What’s the solution?
Thank you

2 Likes