Attach Images and PDFs to AI Chat

by Froala_marketing

HTML

<link href="https://cdn.jsdelivr.net/npm/froala-editor@5.5.0/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />

<div id="editor">
    <p>Froala Editor is a lightweight WYSIWYG HTML editor written in JavaScript.</p>
  <h3>Before you start:</h3>
  <p>In the JavaScript code, replace <code>sk-or-v1-YOUR_OPENROUTER_API_KEY</code> with your own <a href="https://openrouter.ai/">OpenRouter API </a> key.</p>
  <h3>How to test:</h3>
  <p>Open AI Chat from the toolbar, click <strong>+</strong>, and choose <strong>File</strong>.</p>
  <p>Attach an image, a PDF, or a Word document, then ask a question about it.</p>
</div>

<!-- mammoth.js reads DOCX files. Load it before Froala. -->
<script src="https://cdn.jsdelivr.net/npm/mammoth@1.11.0/mammoth.browser.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/froala-editor@5.5.0/js/froala_editor.pkgd.min.js"></script>

JavaScript

// OpenRouter settings. Replace the key with your own.
const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';
const OPENROUTER_API_KEY = 'sk-or-v1-YOUR_OPENROUTER_API_KEY';
const OPENROUTER_MODEL = 'openai/gpt-4o-mini'; // A model that can read images.

// Turns the prompt and attached files into one OpenRouter message.
// Images and PDFs arrive as base64 and become their own message parts.
// TXT, MD, and DOCX files arrive as textContent, which Froala has
// already added to request.prompt, so they need no extra handling.
function buildMessageContent(request) {
  const binaryFiles = (request.files || []).filter((file) => file.base64);
  if (!binaryFiles.length) return request.prompt;

  const parts = binaryFiles.map((file) => {
    const dataUrl = `data:${file.mimeType};base64,${file.base64}`;

    if (file.mimeType === 'application/pdf') {
      return { type: 'file', file: { filename: file.name, file_data: dataUrl } };
    }
    return { type: 'image_url', image_url: { url: dataUrl } };
  });

  // OpenRouter recommends sending the text first, then the files.
  return [{ type: 'text', text: request.prompt }, ...parts];
}

// Froala calls this function for every AI Chat and AI Assist request.
async function openRouterRequestHandler(request, signal) {
  const hasPdf = (request.files || []).some((file) => file.mimeType === 'application/pdf');

  const body = {
    model: OPENROUTER_MODEL,
    messages: [{ role: 'user', content: buildMessageContent(request) }]
  };

  // Reads PDFs with OpenRouter's free cloudflare-ai parser.
  if (hasPdf) {
    body.plugins = [{ id: 'file-parser', pdf: { engine: 'cloudflare-ai' } }];
  }

  const response = await fetch(OPENROUTER_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${OPENROUTER_API_KEY}`
    },
    body: JSON.stringify(body),
    signal // Lets the Cancel button end the request.
 ...