Cem Kaan
Cem Kaan

Reputation: 2226

How to upload image to strapi?

How can I upload images to Strapi server?

I found an article about how to manage file uploads but I have some questions

Do I need to convert my image to a Base64 string?

My production server will be PostgreSQL. I was planning to store images as Blob. But now it turns out I can only send Form-Data to Strapi servers.

Do I need something like apollo-upload-client?

Note: Currently I use vue-apollo and nativescript-vue as frontend.

import VueApollo from "vue-apollo";
import { ApolloClient, InMemoryCache, HttpLink } from "apollo-boost";
import { setContext } from "apollo-link-context";

Upvotes: 1

Views: 7978

Answers (2)

Juanmabs22
Juanmabs22

Reputation: 1300

Thanks to the answer of @Jim LAURIE I made my node work:


import { GraphQLClient, gql } from "graphql-request"
import { createReadStream } from "fs";

[...]

  const endpoint = 'http://localhost:1337/graphql';

  const graphQLClient = new GraphQLClient(endpoint, {
    headers: {
      authorization: `Bearer ${jwt}`,
    },
  });

  try {
    const data = await graphQLClient.request( gql`
    mutation($file: Upload!) {
      upload(file: $file) {
        id
        name
      }
    }
  `, {
      file: createReadStream(__dirname + '/Strapi/test/picture.jpg') // ⚠ Ensure path is correct or the stream will never send data and you will have Socket Hang out error
  });

    console.info("ID of file:" + data.upload.id);
    console.info(data)
    console.info("data")
  } catch (error) {
    console.error(error)
    console.error("error")
  }

If you don't know how get the JWT check the units testing docs of Strapi, translate to GraphQL should be easy.

Upvotes: 0

Jim LAURIE
Jim LAURIE

Reputation: 4120

If you are trying to upload files with GraphQL, I suggest you check this gist - https://gist.github.com/alexandrebodin/fedc71c8513bfbb6283cc90ae62755c5

You should have all the information you need to achieve that.

Upvotes: 3

Related Questions