Upload file from buffer using upload service

Hello everyone,

I’m getting the profile picture of users who authenticate via third party provider and upload the image to Strapi using the REST API. But I would prefer using the upload service instead of the REST API, as I don’t want to give public users permission to upload. How can I do this in V4?

Here is my current implementation using REST:

module.exports = {
    beforeCreate(event) {

        console.log(strapi)

        const axios = require("axios");
        const FormData = require('form-data');

        if (event.params.provider !== "local") {
            try {
                const img = event.params.data.profile_picture_social;

                async function fetchAndUploadSocialImage(img) {
                    const response = await axios.get(img, {responseType: "arraybuffer"});

                    const form = new FormData();
                    form.append("files", response.data, `useravatar-${event.params.data.username}.jpg`)

                    // How do I upload using upload service?
                    const upload = await axios.post(`${process.env.API_URL}/api/upload`, form).catch((error)=> {
                        console.log(error.response.data.error)
                    })
                }
                fetchAndUploadSocialImage(img);
            } catch (error) {
                console.log(error)
            }
        }
    },
}

I’ve already read through some posts but they’re all outdated and for V3, sadly.

1 Like