Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Messages and Embeds

Files and Uploads

Send and receive files with Telegram and Discord bots - multipart/form-data with FormData and Blob, file_id reuse, getFile downloads, attachment:// references in embeds, size limits and safe filename handling.

Bots send charts, exports, screenshots, logs and generated images, and they receive photos and documents from users. File handling uses a different HTTP encoding from the JSON calls you have seen so far: multipart/form-data, the same format as an HTML file-upload form. Node has everything built in: FormData, Blob and fetch handle the encoding for you. The real work is in the platform rules and in validating files you receive from strangers.

Three ways to send a file on Telegram

Methods such as sendPhoto, sendDocument, sendVideo and sendAudio take the file in one of three forms:

  1. A file_id of a file already on Telegram's servers. This is the fastest: nothing is uploaded again. Every file your bot sends or receives gets an id you can store and reuse.
  2. An HTTP URL that Telegram downloads (limited to about 5 MB for photos and 20 MB for other files).
  3. An upload as multipart/form-data (up to about 10 MB for photos and 50 MB for other files with the standard cloud Bot API).

caption (up to 1024 characters) goes next to the file. To receive files, an update's message carries photo (an array of sizes, the last is the largest), document, video or audio, each with a file_id. Then you call getFile to obtain a file_path and download from https://api.telegram.org/file/bot<TOKEN>/<file_path>. The standard cloud API lets bots download files up to about 20 MB.

Discord attachments

You upload files in the same request that creates the message: a multipart body with a part named payload_json (the normal JSON message) and parts named files[0], files[1], and so on. Reference an uploaded file inside an embed with attachment://filename.png. Each message can carry up to 10 files; the default size limit is about 10 MB per file for current servers, and higher in boosted servers, so read the current documentation before relying on a number. Include an attachments array in payload_json to give each file an id, a filename and a description (alt text).

Multipart in Node

FormData collects fields and files, and fetch sets the Content-Type: multipart/form-data; boundary=... header for you. Never set that header yourself: the boundary is generated and must match the body.

The stand-in server below accepts a Discord-style upload. It parses the request using Node's own web-standard Request.formData().

Node.js A Discord-style multipart upload to a stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same FormData approach works for Telegram: append a chat_id text field and a document file field, then POST to sendDocument. Other parameters that are objects (such as reply_markup) must be sent as JSON strings inside a multipart request, because multipart fields are flat text.

Receiving files safely

Files from users are untrusted input. Whatever you do with them (store, parse, forward), apply these checks before reading the content:

  • Size. Check the declared size first (file_size in Telegram, size on Discord attachments) and refuse files above your limit. Also enforce a limit while streaming, because declared sizes can lie.
  • Type. Do not trust the file name extension or the MIME type the client claims. If your bot reads CSV, parse defensively and fail cleanly; if it handles images, use a real image library.
  • Name. Never use a received file name as a path. ../../etc/passwd or C:\Windows\x must not end up on your disk. Generate your own names (an id plus a known extension).
  • Count and rate. A user can send many files quickly; combine this with the throttling middleware from Middleware and Error Handling.
  • Storage. Do not serve uploaded files back from your domain with a guessed content type. Keep them outside the web root or in object storage.
Node.js Validating an incoming file and simulating getFile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

path.basename after converting backslashes turns ../../etc/passwd into passwd, so the extension check rejects it (no extension) even before anything touches the disk. Layering these small defences is much safer than relying on a single check.

Generating files on the fly

You rarely need a temporary file on disk. Build the content in memory (a CSV string, an SVG, a PNG from a canvas library) and wrap it in a Blob. For big exports, stream to the response instead of building one giant string, and remember that all platform limits apply to the final size. If a result would exceed the limit, send a summary in the message and a link to download the full file from your own server, or split it across several files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you not set the Content-Type header yourself when sending FormData with fetch?

    The header contains a boundary string. fetch creates it together with the body, so a hand-written header would not match.
  2. 2. What is the fastest way to send a file Telegram already has?

    A file_id refers to a file stored on Telegram, so nothing needs to be uploaded.
  3. 3. How does a Discord embed refer to an attached image?

    Uploaded files are referenced as attachment://name inside the embed's image or thumbnail url.
  4. 4. Which is unsafe when saving a file received from a user?

    A crafted name like ../../etc/passwd can escape your upload directory. Always generate or sanitise names.

Summary

  • Files travel as multipart/form-data; Node's FormData, Blob and fetch handle the encoding (let fetch set the boundary).
  • Telegram accepts a file_id, a URL or an upload; receive files with getFile then a download URL.
  • Discord uses payload_json plus files[n] parts and attachment://name references.
  • Send object parameters such as reply_markup as JSON strings in multipart requests.
  • Treat received files as hostile: check size, type and count, sanitise names, and keep them away from your web root.

Next: Message Length and Rate Limits