Back

# Issue: Unable to Upload Image Buffer to Appwrite Storage

  • 0
  • Webhooks
  • Web
  • Storage
Ben
1 Jul, 2024, 04:50

I set up a webhook that will receive image metadata that contains image URL. I convert it to a image buffer and try to upload it to Appwrite Storage, but I'm encountering errors. I upload it using the Appwrite SDK.

The Error happens at this line of code : "const inputFile = InputFile.fromBuffer(buffer, imageName);" TypeError: Cannot read properties of undefined (reading 'fromBuffer')

TypeScript
const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();
const sdk = require('node-appwrite');
const { InputFile } = require('node-appwrite');
const https = require('https');

app.use(bodyParser.json({ limit: '50mb' }));

const client = new sdk.Client()
    .setEndpoint(process.env.APPWRITE_API_ENDPOINT)
    .setProject(process.env.APPWRITE_PROJECT_ID)
    .setKey(process.env.APPWRITE_API_KEY);

const storage = new sdk.Storage(client);
const databases = new sdk.Databases(client);

function fetchImage(url) {
    return new Promise((resolve, reject) => {
        https.get(url, (response) => {
            if (response.statusCode !== 200) {
                reject(new Error(`Failed to fetch image: ${response.statusCode}`));
                return;
            }

            const data = [];
            response.on('data', (chunk) => {
                data.push(chunk);
            });

            response.on('end', () => {
                resolve(Buffer.concat(data));
            });
        }).on('error', reject);
    });
}

async function uploadImage(imageUrl, imageName, bucketId = process.env.BUCKET_ID) {
    try {
        const buffer = await fetchImage(imageUrl);

        console.log('Image fetched, buffer size:', buffer.length);

        const inputFile = InputFile.fromBuffer(buffer, imageName); 
        const result = await storage.createFile(bucketId, sdk.ID.unique(), inputFile);

        return result;
    } catch (error) {
        console.error("Error uploading image:", error);
        throw error;
    }
}
TL;DR
Issue: Developer is unable to upload image buffer to Appwrite Storage using the Appwrite SDK. Error arises at the line "const inputFile = InputFile.fromBuffer(buffer, imageName)" with TypeError: Cannot read properties of undefined (reading 'fromBuffer'). Solution: Ensure that the InputFile class is properly imported from 'node-appwrite' library. Double-check the documentation and verify the correct usage of the function.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more