how tc upload image in graphql variables with axios and formdata

Viewed 43

Upload file with axios , graphql and formdata##

I want to upload image in the nodejs server by graphql and formdata with axios and this is my way but not working , I think this problem is in append to form data but I can not find why or in axios fetch data

Code

 let data = {
              query: `
              mutation Mutation($image: Upload!) {
                multimedia(image: $image) {
                  status
                  message
                  token
                }
              }`,
              variables: {
                image: null,
              },
            };
            let map = {
              0: ["variables.image"],
            };
            const FormD = new FormData();
            FormD.append("operation", JSON.stringify(data));
            FormD.append("map", JSON.stringify(map));
            FormD.append(0, element.file, element.file.name);
            console.log(FormD);
            await axios({
              url: "/",
              method: "POST",
              headers: {
                token: token,
                "Content-Type": "multipart/form-data",
              },
              data: FormD,
              onUploadProgress:ProgressEvent=>{
                element.loaded=ProgressEvent.loaded/ProgressEvent.total*100
              }
            })
      .then((response) => {
        if (response.data.errors) {
          const { message } = response.data.errors[0];
          toast.error(message);
        } else {
          setLoadedFiles(tempLoadedFiles);
        }
      })
      .catch((error) => {
        console.log(error);
      });

but the response is

response

{
    "message": "Request failed with status code 400",
    "name": "AxiosError",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {
            "FormData": null
        },
        "headers": {
            "Accept": "application/json",
            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjY3NWZiODkwNjY0N2RlZWRmMTM5ZiIsImlhdCI6MTY2MDg5NTgzMSwiZXhwIjoxNjYzNDg3ODMxfQ._5gmsMHD_HRokvoopKOit1n8YhG_sP3oR_OLRSXqZTo"
        },
        "baseURL": "http://localhost:4000/graphql",
        "url": "/",
        "method": "post",
        "data": {}
    },
    "code": "ERR_BAD_REQUEST",
    "status": 400
}

thanks for your answer

1 Answers

I fixed this issue , dont use

let data = {
              query: `
              mutation Mutation($image: Upload!) {
                multimedia(image: $image) {
                  status
                  message
                  token
                }
              }`,
              variables: {
                image: null,
              },
            };

and replace it in the axios

 await axios({
          url: "/",
          method: "post",
          headers: {
            "token": token,
            "Content-Type": "application/json",
          },
          data: {
            query: `
            mutation Mutation( $image : Upload!) {
              multimedia(image: $image) {
                status
                message
              }
            }`,
            variables: {
              image: element.file,
            },},
          onUploadProgress: (ProgressEvent) => {
            tempLoadedFiles[index].loaded =
              (ProgressEvent.loaded / ProgressEvent.total) * 100;
          },
        })

and it's working...

Related