New Froala Editor v5.6.0 is here – Learn More
Froala Documentation
- Installation Guides
- Browser Support
- Languages Support
- Shortcuts
- Activation
- Examples
- Customize the Editor
- Use-cases
- Plugins
- APIs
- Development Frameworks
- Server Integrations
- Server SDKs
- Migration Guides
- Changelog
- Tutorials
Attach Images and PDFs to AI Chat
Attach Files to AI Chat
Let users attach images, PDFs, and documents in the AI Chat panel and ask questions about them. This example sends each file to OpenRouter in a format the model can read.
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>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
<script>
// 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.
});
if (!response.ok) {
throw new Error(`OpenRouter API error ${response.status}`);
}
const data = await response.json();
return (data.choices?.[0]?.message?.content || '').trim();
}
new FroalaEditor('#editor', {
toolbarButtons: ['aiChatAssistant', 'aiAssist', '|', 'bold', 'italic', 'formatUL', '|', 'undo', 'redo'],
heightMin: 300,
aiSupplementalTermsAccepted: true, // Required for every AI feature.
aiChatStreamResponse: false, // Keeps this example focused on files.
aiChatSupportedFileTypes: ['pdf', 'docx', 'txt', 'md', 'jpg', 'jpeg', 'png', 'gif', 'webp'], // The default list.
aiChatMaxFileSizeMB: 20, // The default limit.
aiAssistRequest: openRouterRequestHandler
});
</script> In this example
Froala reads each attached file in the browser and passes it to your aiAssistRequest handler in request.files. The file type decides what your handler receives.
- Images and PDFs arrive as
base64data. The handler sends them to OpenRouter as separate parts of the message. - TXT, MD, and DOCX files arrive as
textContent. Froala adds their text torequest.promptfor you. - PDFs pass through OpenRouter's free PDF parser, so the model reads them as text.
- Two options,
aiChatSupportedFileTypesandaiChatMaxFileSizeMB, control which files users can attach and how large they can be.
How it works
How an attached file reaches the model
- The user attaches a file in AI Chat
- Froala reads the file in the browser
request.files - Text files join the prompt
textContent - Images and PDFs become message parts
base64 - OpenRouter returns one answer
return answer
Each file arrives in one of two shapes
Every entry in request.files has a name and a mimeType, plus one content field.
base64holds the raw file data for images (JPG, JPEG, PNG, GIF, and WEBP) and PDFs.textContentholds the text of TXT and MD files, and the HTML of DOCX files.
Text files are already in the prompt
Froala adds each text file to the context section of request.prompt, labeled with its file name. Your handler forwards the prompt as it is, which keeps buildMessageContent short.
Images and PDFs become message parts
OpenRouter accepts a message made of parts. buildMessageContent puts the prompt first, then adds an image_url part for each image and a file part for each PDF. Froala sends base64 as raw data, so the handler adds the data: prefix with the file's mimeType.
A parser turns PDFs into text
When a PDF is attached, the handler adds OpenRouter's file-parser plugin with the free cloudflare-ai engine. OpenRouter converts the PDF to text before the model reads it. For scanned PDFs, switch the engine to mistral-ocr, which reads text from page images and is billed per page.
DOCX support uses mammoth.js
Froala converts Word files with mammoth.js, which it finds through the importFromWordMammoth option. That option reads window.mammoth when Froala loads, so the mammoth script tag goes before the Froala script tag.
Froala checks type and size first
aiChatSupportedFileTypes sets the extensions the file picker accepts. The default list is pdf, docx, txt, md, jpg, jpeg, png, gif, and webp. aiChatMaxFileSizeMB sets the size limit, which defaults to 20 MB. A larger file shows a "File too large" message on its chip in the composer.
Good to know
- This example calls OpenRouter from the browser, so anyone who opens the page can read your API key. Use it for prototypes, demos, and model testing. For production, keep the key on your server and follow the Custom Backend example.
- Attached files go to OpenRouter and the model provider. Let users know this before they share sensitive documents.
- Image reading depends on the model.
openai/gpt-4o-minireads images. When you switch models, pick one that lists image input on OpenRouter. - This example turns streaming off to keep the code focused on files. The Stream AI Chat Responses example shows how to add streaming back.
- Froala AI features stay inactive until you set
aiSupplementalTermsAcceptedtotrue. Setting it confirms that you accept the Froala AI Supplemental Terms.
Related AI examples
- Stream AI Chat responses with OpenRouter
Show answers in the chat panel as the model writes them. - Direct OpenAI API integration
Call OpenAI from the browser with a short handler. - Custom backend with validation and event hooks
The production pattern with your key kept on the server. - Standard endpoint with custom formats
Connect to an existing API using options only.
Want to see AI Chat in action? Try it in our overview demo.
Related Plugin:
AI Assist Whats on this page hide