Next.js Discord

Discord Forum

Discord Webhook with Images

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I've been trying to make a page that can send a Discord webhook with a selected image. I couldn't figure it out.
I'm so far able to send a message, but when it comes to images, it's just not working.
My code:
export default async function handler(req, res) {
    if (req.method === "POST") {
        const webhookUrl = process.env.DISCORD_WEBHOOK_URL;
        const file = req.files?.file;

        let payload = {};

        if (file) {
            const filename = file.originalFilename || "attached_file";
            const contentType = file.mimetype;

            // Create a PassThrough stream for the file
            const fileStream = new PassThrough();
            fileStream.end(file.buffer);

            // Create a form-data instance
            const formData = new FormData();
            formData.append("content", "");
            formData.append(
                "embeds",
                JSON.stringify(...jsondata)
            );
            formData.append("attachments", fileStream, {
                filename,
                contentType,
            });

            // Set up the axios config
            const config = {
                headers: {
                    ...formData.getHeaders(),
                    "Content-Length": formData.getLengthSync(),
                },
            };
            // Send the request with streams
            try {
                const response = await axios.post(webhookUrl, formData, config);
                res.status(200).json({ success: true });
            } catch (error) {
                //handle error
            }
        } else {
            payload = { content: req.body.content };

            try {
                const response = await axios.post(webhookUrl, payload);
                res.status(200).json({ success: true });
            } catch (error) {
                //handle error
            }
        }
    } else {
        //handle error
    }
}

Any and all help is appreciated 🙏

0 Replies