Is it possible to run a script every time an image uploaded

Hello,

Certainly! You can integrate your Python script with Strapi to analyze images and store the data in your Strapi database. Let’s break down the steps:

Uploading Images to Strapi:
First, you’ll need to upload the images to Strapi. You can do this by sending a POST request to the /upload endpoint. Make sure to include the image file in the request body as a form-data field named files.
Here’s an example using Python’s requests library:

import requests

url = 'http://localhost:1337/upload'
headers = {'Authorization': 'Bearer your_jwt'}
files = {'files': ('filename.jpeg', open('filename.jpeg', 'rb'), 'image/jpeg')}
response = requests.post(url, files=files, headers=headers)

The response.text will contain the ID of the uploaded image in the Strapi Media Library.

Creating Entries with Image References:
Once you have the image ID, you can create an entry in your collection type (e.g., logs) and reference the image using its ID.
For example:

payload = {
    "Type": 'info',
    "Message": 'lorem ipsum beep bop',
    "Screenshot": 1,  # Replace with the actual image ID
}
response = requests.post('http://localhost:1337/logs', json=payload)

Running Python Script on Image Upload:
Strapi itself does not directly execute Python scripts upon image upload. However, you can set up a separate process (e.g., a cron job or a separate server) that monitors the Strapi database for new image uploads.
When a new image is uploaded, your external process can invoke your Python script to analyze the image and update the relevant Strapi entry.

1 Like