Zachary
Zachary

Reputation: 21

Upload image to strapi with external link

What is a proper way to upload an external image via URL into strapi on backend-side?

I had tried to load image with node-fetch and processed it with buffer()/blob()/blob().stream() and then passed it into strapi.plugins['upload'].services.upload.upload(). Also tried to generate FormData in node.js and passed it into upload service but still didn't help.

How to convert image buffer from fetch into suitable type for upload service?

Upvotes: 2

Views: 3941

Answers (1)

Georgiy Bukharov
Georgiy Bukharov

Reputation: 396

I used axios and it was on client, but you can try in on server too I think. This worked for me:

Fetch an image and create File instance from it

async getImage(imageUrl, imageName) {
  const response = await axios.get(imageUrl, { responseType: 'blob' });
  const mimeType = response.headers['content-type'];
  const imageFile = new File([response.data], imageName, { type: mimeType });
  return imageFile;
}

GraphQL API query

{
  query: `
    mutation($files: [Upload!]!) {
      multipleUpload(files: $files) {
        id
      }
    }
  `,
  variables: {
    files: [
      // your files to upload
    ]
  }
}

Then I called this mutation and it worked perfect.

Resources that I used to find this solution:

https://www.freecodecamp.org/news/how-to-manage-file-uploads-in-graphql-mutations-using-apollo-graphene-b48ed6a6498c/

Client side convert png file stream into file object

https://github.com/jaydenseric/graphql-multipart-request-spec

Upvotes: 2

Related Questions