Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 12. Files and Temporary Files

The images, audio, video, and models in the previous chapter all have a file behind them. This chapter puts the file itself at the center. It does not care whether it is an image or a recording, only where it comes from, where it lands, and when it disappears.

A file value is unlike every earlier value. A number sent to the server with a request is that number, and it is gone once used; what a file sends with a request is only the name of “some file somewhere”, while that file still sits on disk, where it can be read by others, deleted by the cleanup routine, or overwritten by the next upload. What the handler function gets is that name, not the file itself.

The difference runs deeper than one layer. Numbers and strings are “values”: copy one, pass it to someone else, store it in a database, and it is still that content; a file is a “reference”: what gets passed is an address, and the content stays where it is. Whether a file “still exists right now”, “who has the right to send it to others”, and “when it will be cleaned up” are all decided by this application’s configuration; the handler function holds only that name.

There is one more consequence. A file is the only kind of value that “can still change after being sent to the front end”. A number the handler function computes does not change on its own, but the file pointed to by the path the handler function received may be deleted by the cleanup routine two minutes later, or replaced with different content by the next upload. If two uploads have the same content hash, the path does not even change. This chapter is about “who manages a file’s lifecycle”.

Broken down: how many files are allowed (fileCount), what is passed to the handler function (type), and which types are allowed (fileTypes). Add four knobs on top: which directory files land in, how large they can be, how often the cache is cleaned, and which directories beyond the cache may be served. The example adds a tenth block to the workbench, the file module, which lays all of these out at once.

12.1 File Count and Type Limits

File is the main component of this chapter; its parameter list is short, and the first three decide the contract.

                one = gr.File(
                    fileCount: "single",
                    fileTypes: [".txt"],
                    type: "filepath",
                    height: 240,
                    label: "Single file (path): txt only");

fileCount has three values: single for one file, multiple for several, directory for a folder. It governs “how many are allowed”, but this parameter also changes the look of the UI along the way, more than you would expect. Figure 12-1 places the three modes side by side: how many each allows, what the entry point is, what structure is passed to the handler function, and which mode alone has handles and deletion.

Figure 12-1 The three values of fileCount and the structure each passes to the handler function

The single-file mode has no delete button and no reordering handle. With only one file, deleting leaves it empty, and there is nothing to reorder. Only the multiple-files mode needs these. Figure 12-2 shows the example after “Load a group” has been clicked: three files in a column, each row with two small dots on the left as a drag handle, 438.0 B plus a downward arrow on the right, and deletion at the far right.

The three modes are not just a switch for “how many are allowed”; they correspond to three different UI intentions. Single file means “exactly one, no more”: changing an avatar, uploading one config file, naming one output directory — the user has one thing in mind, and giving one more is a mistake. Multiple files means “a batch”: several logs to merge, several images to print together, where order may matter, so handles are needed. Directory means “a whole package”: the source files of an entire project, a complete set of assets, where the user does not want to pick one by one, and the folder itself is the unit they want to express.

The cost of picking the wrong mode is not paid at compile time, it is paid by the user. Write an input meant for a batch as single file and the first file is quietly replaced when the user drags in a second one, with no notice at all; write an input meant for one file as multiple files and the handler function has to decide on its own “which one to use when three are given”, a decision the UI should have made.

fileCount also has a side effect that is easy to miss: it decides how the block’s height grows. A single-file block has a fixed height: set height: 240 and it is 240, taking up that much even when empty; a multiple-files block grows with the number of rows — three files give the height in Figure 12-2, ten files hit the height limit and then scroll internally. Place two blocks side by side and this difference keeps them from lining up. The example gives the two single-file blocks the same height precisely to align them; the row with a group of files and a directory each sets 230 for the same reason.

Figure 12-2 A group of files: handles, byte counts, download, and delete all on the row

The handle appears only when allowReordering: true is set. The example’s three files set this parameter, so they can be dragged into a new order; remove that line and the handle disappears, and the order is fixed in the array. This switch takes a boolean, but it decides “whether the user can change the order”, and that order directly determines the array order the handler function receives. It is not decoration.

fileTypes is the second parameter; it accepts a list of extensions or categories, and writing [".txt"] means accepting text only. It has two effects, one visible and one hidden. The visible one writes the extension into the browser’s file picker, so the user only sees txt when it opens; the hidden one is that the front end checks again, so dragging in a csv is stopped on the spot.

Figure 12-3 shows the rejection. The block is empty, with a red “Error” marker in the middle and a notice in the top-right corner, Invalid file type: plan.csv. Only .txt allowed. It says “this file type is wrong, only .txt is allowed”, naming both the file and the rule.

Figure 12-3 Wrong type: the front end rejects it on the spot, the value in the block does not move

This check happens in the browser; the server never receives this upload at all. In other words, fileTypes is a rule shown to the user, not a security boundary. Bypass the UI and push a csv straight into the upload endpoint, and the server still accepts it, the handler function still gets the path. One script call to the upload endpoint is enough to prove it. That csv slips quietly into the cache with no notice at all.

Keep this distinction in mind. To build an application that “only handles txt”, writing fileTypes is not enough; the handler function has to judge once more on its own: is the extension right, can the content be read. The former is experience, the latter is correctness, and their costs are far apart. The former is one line of parameters, the latter a few lines of code plus an error message — but only the latter can guarantee that what you get is what you think it is.

The example’s handler function does only the experience half, because it is a demo; in a real product you should at least check the extension before reading the file, and be ready to catch the case of “a binary file with a changed extension” while reading it. An image renamed to .txt passes the extension check, and ReadAllLines throws. What the user should see then is not a stack trace, but a line saying “this file cannot be read”.

fileTypes has two spellings: extensions with a dot ([".txt"]) and category names (["image"], ["text"], ["video"]). Extensions are precise, categories are loose. ["text"] lets in txt, md, csv, and json together, while [".txt"] lets in only txt. The example uses the extension, because this block should accept plain text only; the image-like components in the previous chapter used categories, because what they want is “all images”. Which one you pick depends on whether you mean to express “which files” or “which class of files”.

allowReordering is the third parameter, false by default. Set it to true and a drag handle of two small dots appears on the left of each row in a multiple-files list, letting you drag to swap positions; set it to false or leave it out and the handle does not appear, and the order is whatever order the user picked files in. This switch looks small, but it decides one thing: whether the order is “actively arranged by the user” or “inherited from the sequence in which files were selected”. Turn it on if you want to merge files in the order the user gives; leave it off if order does not matter. A handle you can drag but that does nothing is more confusing than no handle at all.

12.2 File Value Types and Return Structures

type decides what is passed to the handler function. It has two values, which in C# are two completely different things.

Figure 12-4 The two values of type: both routes put the file into the cache first

Write filepath and the handler function receives a string, the path of that file in the cache directory. Write binary and it receives a byte array, with the whole file in memory. The middle cell of Figure 12-4 is shared by both routes. Either way the file first lands in the cache by content hash; the only difference is whether the handler function gets a path or the content.

The example puts the same brief.txt into two blocks and reads each once. The path block shows 387 bytes · 6 lines · first line "Wrapping rules (first draft)", followed by a long cache path; the byte block shows 387 bytes, plus the file’s first four bytes 57 72 61 70. That is the UTF-8 encoding of the character “W”: the first three bytes are the character, the fourth is the start of the next one.

Figure 12-5 The same file, two ways of passing the value; the path block also gives a long path

Figure 12-6 Reading binary: 387 bytes in hand, no path

How to choose? Pick filepath if another program will process this file next (read lines, compute a hash, convert format). You hold only a string, so no matter how large the file it costs no memory; the price is that the file has to keep existing, and once cleaned up there is nothing left to read. Pick binary if you will work on it directly in memory (decompress, encode, slice). It saves opening the file a second time, at the price of memory. A 500 KB file is a 500 KB array inside the handler function.

fileCount and type together decide the signature. The four combinations below are the ones written most often, and the multiple-files cell is the one most often written wrong.

fileCounttypeWhat the handler function receives
singlefilepathstring?
singlebinarybyte[]?
multiplefilepathstring[]?
directoryfilepathstring[]?

Multiple files pass an array to the handler function, not a list. Writing List<string> compiles, but at runtime it reports a very blunt message: what is passed to the handler function is System.String[], which cannot accept the type List<string>. What the component sends is an array, and you have to be able to receive it.

The example does not use the multiple-files-with-binary cell, and in practice it is rare too. Reading several files entirely into memory at once costs the number of files times their size, and multiple-files situations are usually exactly those with many large files. To handle them one by one, filepath with a loop is steadier.

The directory cell deserves its own note. On the server it is the same route as multiple files: both pass an array of paths to the handler function. The difference is entirely on the front end. Multiple files lets you pick several files at once; directory lets you pick only one folder and then collects all the files inside it. So the handler function needs no second set of logic for directories: accepting a string[] covers both sources.

string ReadGroup(string[]? paths) => ReadPaths("Group", paths);

One line. ReadPaths reports one line per file: name, byte count, extension. The directory mode uses the same line, only with the title changed to “Directory”.

All parameters are nullable, because every block can be empty. The empty value is part of the contract. No file means no file, and the handler function has to decide on its own what to say then. The example’s choice is to write “no files yet” into the panel, so that emptiness is visible, rather than let the handler function receive an empty string and guess among a pile of ifs whether it was “not passed” or “passed an empty file”.

The two sources of an empty value need to be kept apart. One is “the user never put anything there”; the other is “they did, but the file is gone now”. The second case also depends on the page. Refresh once and the block is empty, the handler function gets null, the same as never having put anything; without a refresh the block still shows that file name and the value is still there, but the file underneath has already been deleted by the cleanup routine.

The latter is what this chapter really has to guard against, and it cannot be guarded against inside the handler function. Click “Read single” and the handler function is never called at all. Before passing the value to the handler function, the framework first moves this file into the cache; if it cannot, it throws FileNotFoundException, leaves an error in the UI, and the panel stays on its previous line. Figure 12-10 shows exactly that. The block still reads brief.txt, the returned line is still the previous result, with a red “Error” marker added beside it.

So a check like “test whether the file exists before reading” has no place here; it is never your turn to judge. There are only two things you can do: do not treat a cache path as storage; and if you really need to keep a file, copy it into your own directory the moment you get it.

One more thing to know about the binary cell. It reads the whole file into memory, so the larger the file, the more memory the handler function occupies — and that occupancy multiplies by the concurrency count. Ten people uploading 100 MB files at once means 1 GB of arrays on the server. filepath has no such problem: a hundred people uploading at once still means only a hundred strings in memory. That is the first thing to weigh when choosing type: are the files large, are there many users.

One thing to watch in real use of the directory cell. The array passed to the handler function holds every file in the folder, including those in subdirectories and those you did not expect (.DS_Store, Thumbs.db, temporary files left by editors). The example’s ReadPaths reports one line per file, so the user sees those extras; in a real product, either filter them or tell the user plainly that “every file in this folder will be read”.

12.3 UploadButton and DownloadButton

File is “a container”: put files in and watch them line up in a column. UploadButton and DownloadButton are actions: a button, one click, one thing happens.

                upload = gr.UploadButton("Upload button", fileCount: "multiple", fileTypes: [".csv"], type: "filepath");
                download = gr.DownloadButton("Download manifest", value: FileDesk.Write("(no manifest generated yet)"));

The parameter list of UploadButton is the same as the first few of File: fileCount, fileTypes, type. The difference is in the UI. It has no preview area, no file list; clicking opens a picker, and once you choose, it uploads, with the value recorded on the button itself. The example’s upload button accepts csv only, multiple files; Figure 12-7 shows it after a click. The panel reads “Button upload plan.csv”.

Figure 12-7 The upload button: the button itself is the entry point, and the file list is not in the UI

Why have such a thing? Because sometimes what you want is the action “import”, not “this pile of files”. An import button plus one line saying “what was imported last time” is far cleaner than a file list taking up half the screen; once a file is uploaded it should be processed, with no need to keep it sitting in the UI for people to look at.

The upload event of UploadButton is its main entry point, and the handler function receives an array of paths (when fileCount: "multiple"). The example binds it.

    files.Upload.Upload(OnButtonUpload, [files.Upload], [files.Echo], apiName: "Button upload");

DownloadButton is the reverse action: it sends a file to the browser to be saved. Its value is a path, and one click downloads that file. There is one limitation here that the example ran into. value must exist at construction time — a placeholder file will do; a button built empty, whose value a handler function later swaps in, downloads nothing when clicked. So the example first writes a file containing “(no manifest generated yet)” as a placeholder, and swaps in the real one after the manifest is generated.

The reason is not hard to guess. The button has to know “which file it holds” at page load before it can wire up the download route; a button that never had a value has nothing on the front end to wire to, and giving it a value later only changes a field it does not watch. The way around it is simple: give it a placeholder file, or point it at something that really exists from the start. The placeholder’s content gets moved into the cache, so it too gets cleaned up; but after cleanup the button is still in a “wired for download” state, just without that placeholder file. In the example the placeholder really is cleaned up after two minutes, and clicking download then yields an error page. That is exactly what 12.5 covers.

The value of DownloadButton can also be swapped by a handler function; the example’s “Generate manifest” works like the following. The same handler function’s return values are written into both the file block and the button. Both components get the same path and each moves it into the cache once, yet they land in the same directory, because the content is the same and the hash is the same.

The output of File can be downloaded too; the difference is “visibility”. File lays the file out, so the user can see its name, see its size, click the arrow on the row to download, or do nothing at all; DownloadButton has only a button, click or no click. Use File for “the result is here, you can take it”; use DownloadButton for “here is this one file”.

The division of labor among the three components: File handles a visible group of files, UploadButton handles one import action, DownloadButton handles one download. The same file can be written into two of them at once. The example’s manifest appears in both the file block and the download button — two ways of “taking it away”.

12.4 Upload Destination and Size Limits

Where do files land? By default they land in a gradio folder under the system temporary directory, which on Windows is C:\Users\<username>\AppData\Local\Temp\gradio; if the environment variable GRADIO_TEMP_DIR is set, they land in that directory. The example changes it to a folder beside the program itself, so readers can open it and look.

// The four knobs for files: destination, limit, cleanup cadence, and the directories allowed to be served out.
demo.UploadFolder = Path.Combine(AppContext.BaseDirectory, "cache");
demo.MaxFileSize = 512 * 1024;
demo.DeleteCache = new DeleteCacheSettings(TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(120));
demo.AllowedPaths = [FileDesk.Folder];

These four lines sit after gr.Blocks() and before using (demo). They are application-level settings, not component parameters. Where a file lands is the application’s business, not any single block’s.

The structure of the destination is one level deeper than you would expect. Upload a brief.txt and its path in the cache is cache\c519ef57…c97e\brief.txt, one level more than cache\brief.txt. The middle level is the content hash, 64 hexadecimal characters long. Three benefits come from this: the same content uploaded twice takes only one slot; the URL cannot be guessed from the file name; and the question “who does this file belong to” is answered by “is it under this directory”.

Files with different names can live under the same hash directory. When the content is the same but the names differ, both are kept and share one hash directory. Conversely, change one character and upload again: the hash changes, so it is another directory, another file. The cache recognizes by content, not by name.

Recognizing by content has two direct consequences, both worth thinking through before writing an application. First, upload the same file ten times and there is only one copy on disk; the second through tenth uploads take almost no time. What is saved is everything beyond bandwidth. Second, “the path changed” does not mean “the content changed”. Upload the same content again and the path is identical, so the front end cannot tell the difference, and the change event may not even fire. To judge “did the user upload again”, looking at the path is useless; you have to look at something else.

The hash layer has one more layer of salt. Each process generates a random piece at startup and mixes it into the hash, so the same file gets a different path when run today than when run tomorrow. The point of this design is that “an address cannot be computed in advance”. Without the salt, anyone could compute a file’s hash and write out the address before the file even exists. The cost is that after a restart all old paths become invalid, while those files are still in the cache, just with nobody pointing at them anymore. The cleanup routine collects them, so this does not turn into a pile of garbage, but it also shows how short-lived a path is: it does not even survive one restart.

The destination is usually left alone in production. The default temporary directory is managed by the operating system, and cleanup tools know where it is; after changing it to the program directory, a program installed under C:\Program Files may not even have write permission. What needs changing then is the installation method, not this line of configuration. The example changes it to the program directory only so readers can open the folder and see those hash directories with their own eyes.

MaxFileSize is the second knob, in bytes. The example writes 512 * 1024, that is, 512 KB. What happens when it is exceeded? Two gates, first loose then tight.

The first is on the front end. Figure 12-8 shows a 542 KB large.txt pushed in. The block is empty, with a red “Error” marker in the middle and a notice in the top-right corner, File(s) exceed the maximum allowed size of 512.0 Kb: "large.txt", with both the limit and the file name in it.

Figure 12-8 Over the limit: the block is empty, and the notice states the limit and the file name

The second is on the server. When the front end cannot stop it (say a script posting straight to the upload endpoint), the server measures as it reads, stops on the spot once over the limit, and returns 413 with File size exceeded maximum allowed size of 524288 bytes. The number in that line is a byte count, not KB: 512 times 1024 is 524288. Both routes have to block, because the front-end one blocks mistakes, while the server one protects the disk.

When “measuring as it reads”, an oversized file is not first fully written to disk and then deleted; writing stops at the limit, so the disk it occupies is at most the limit. Writing null (that is, leaving this parameter unset) means no limit, and anyone can fill the disk with a 10 GB file. That is something a reverse proxy or your own middleware should handle, not something to expect from the component.

12.5 Cache Cleanup and Allowed Paths

The third knob is DeleteCache, with two time parameters: how often to check, and how old a file must be before it is deleted. The example checks every 20 seconds and deletes files older than two minutes. That cadence is deliberately turned up; a normal application would not set it this way.

Leave this parameter unset and nothing in the cache is ever deleted; everything stays until you clear it yourself. Once set, the application periodically sweeps the files it wrote itself and deletes those past their age; when the application stops, the ones it remembers are deleted along with it. Note the qualifier “it wrote itself”: cleanup only touches files the application has recorded, and will not delete things others placed in the same directory.

The two times each govern one thing; do not mix them. The first is “how often to look”, which decides the delay before deletion. With 20 seconds, a file is deleted at the latest 20 seconds after it expires, 10 seconds on average. The second is “how old counts as old”, measured from the file’s last write time, not from its upload time. (20, 120) means: look every 20 seconds, and delete anything untouched for over two minutes. So the moment a file truly disappears falls between 120 and 140 seconds, not at one precise instant. Keep this in mind when writing docs about “how long until a file expires”: do not present a planned value as a promised one.

Why is age measured from “last write” rather than “creation”? Because the cache stores by content. The same content may be shared by many operations, and one new reference amounts to writing it once more. Measured from last write, a file in use is not deleted; measured from creation, a template file used for three days would vanish on the third day. This choice has no effect on a flow that “uploads one file and uses it right away”, but a large effect on a flow that “keeps a long-lived asset in the cache”. So long-lived things do not belong in the cache.

Writing null (leaving this parameter unset) turns cleanup off, and the cache only grows; that is convenient in development (files survive a restart), but in production it will fill the disk sooner or later. To leave an opening for “cleanup managed by someone else”, do not set it, and instead bring the directory under the system’s temporary-file cleanup policy. That policy does not know “which files the application is using”, so do not expect it to be precise.

Both cache screenshots upload the same brief.txt into the single-file block, one right after uploading, one two and a half minutes later. Check the cache immediately after the upload: 15 files, 279,575 bytes, with brief.txt the most recently written; click “Read single” on that same value and it reports 387 bytes, 6 lines. Check again two and a half minutes later: 11 files, 278,691 bytes, and the most recently written is something else; the block still reads brief.txt, and clicking “Read single” again leaves the returned line unchanged, with a red “Error” marker added beside it.

Figure 12-9 Checked right after upload: fifteen files in the cache, the newest one just uploaded

Figure 12-10 Two and a half minutes later: the file is cleaned up, the block still shows the name, and reading again errors

A cache path is a promise that “it is here right now”. Write it into a database, into a config file, send it to someone else, and a while later it is a dead link. To keep a file, you have to copy it into your own directory inside the handler function. The example’s out directory is used exactly this way: the generated manifest is written there first, then moved into the cache by the component.

The copy moved into the cache is cleaned up too. In the round of Figure 12-10 the cache drops from 15 files to 11; of the four that disappeared, only one was just uploaded, and the other three were temporary files left by other modules. The cache treats everything that lands in it the same.

The fourth knob is AllowedPaths, which answers a different question: besides the cache directory, which other directories may the file endpoint serve. By default, none at all. The application serves only files it wrote itself, and gives out nothing from anywhere else.

The example adds the assets directory, so the UI gains a link “Original asset brief.txt” pointing at /gradio_api/file=<path>. Clicking it opens that file, because it is in an allowed directory. Remove that line and the same link returns 403, with a body of File not allowed: ... plus that path.

The cost of this switch needs to be stated plainly. Allowing a directory means letting anyone who can reach this application read every file in that directory. Allowing C:\Users\you\Documents puts the whole Documents folder on the web. If you allow anything, allow a dedicated directory holding only files meant for outsiders; do not allow a home directory, do not allow the program directory.

12.6 Import, Upload, and Clear Return Values

File has five events: change, upload, clear, delete, download. The names are easy enough, but which ones actually fire and what they bring back when they do has to be tried one by one.

The example binds three: upload, change, and delete, on the single-file block, the group-of-files block, and the upload button respectively.

    files.One.Upload(OnUpload, [files.One], [files.Echo], apiName: "Single upload");
    files.One.Change(OnFileChange, [files.One], [files.Echo], apiName: "Single change");
    files.Group.Upload(OnGroupUpload, [files.Group], [files.Echo], apiName: "Group upload");
    files.Group.Delete(OnGroupDelete, [files.Group], [files.Echo], apiName: "Delete one");
    files.Upload.Upload(OnButtonUpload, [files.Upload], [files.Echo], apiName: "Button upload");

A single upload fires two events, upload and change. The former means “the file landed”, the latter “the value changed”; by outcome they are the same thing, by semantics two different angles. Bind upload if you only care that “a new file came in”; bind change if you care “what this value is now”. Binding both logs twice, which is what the example’s single-file block does, so two lines appear in a row on the panel.

Delete one entry from a multiple-files list and what fires are delete and change. delete brings back the array as it stands after the deletion. When the example deletes down to one file, the panel writes “Delete one, 1 left”. That number is what remains, not what was deleted; do not read it backwards.

Click the clear button in the component’s top-right corner and only change fires, bringing back an empty value; the panel writes “Change: value cleared”. The clear signal exists, but this action does not fire it.

Click the download arrow on the right of a file row and the browser saves the file directly; the download event does not fire, so the example does not bind it.

These two are the actual behavior. So the component will not tell you “what the user downloaded”; to log it, place your own button that records a line first and then fetches the file. Likewise, to log “the user cleared it”, bind change and treat an empty value as a clear.

Lay these out in a table and you will not have to flip back to check while using them.

EventWhen it firesWhat it brings back
uploadA file landsThe new path or array
changeThe value changed (upload, delete, and clear all count)The current value; empty after clearing
deleteOne entry deleted from a multiple-files listThe array after deletion
clearNot fired by clicking the clear button—
downloadNot fired by clicking the download link—

The most useful row in this table is change. It fires most often and carries the most useful information: what the value is now. Bind just change if you want “log a line whenever the user touches this block”; only when you want “the user added one” and “the user deleted one” handled separately do you need upload and delete.

That delete brings back the array after deletion is critical when designing the handler function. It does not tell you which entry was deleted. To get that, you have to compare this array with the previous one. The example does not store the previous value, so the panel only writes “how many are left”. To be precise down to “notes.md was deleted”, you have to bring in state, which is a matter for Chapter 14.

UploadButton has fewer events: upload, change, click. upload is the main one, firing once when a selection finishes, bringing back an array of paths. click is still useful when “the same file was selected”: the value has not changed, so upload may not fire, but the user did click.

The handler function signature for an event follows its component. A single file takes string?, multiple files and buttons take string[]?. Get it wrong and it does not fail silently; it throws a type-conversion error, the same one as in 12.2.

12.7 Output Files and Download

The inbound route is done; the outbound one has to answer “where is the file” too.

The handler function returns a path, and the component does one thing after catching it. If that path is not in the cache directory, it copies the file into the cache and sends the address of the cached copy to the front end. So after returning out\sheet.txt, the address of that file in the UI is cache\<hash>\sheet.txt, not out\sheet.txt.

(string, object, object) MakeSheet(string[]? paths)
{
    var sources = paths ?? [];

    if (sources.Length == 0)
    {
        return ("**Manifest** no usable files: load a group first, or drag a few files into the group.", gr.Skip(), gr.Skip());
    }

    var path = FileDesk.Write(FileDesk.Sheet(sources));

    return ($"""
        **Manifest** {FileDesk.Describe(path)}

        Written to `{path}`; after it returns, the component moves it into the cache.
        """, path, path);
}

Three return values: one line for the panel, the manifest file block’s value, and the download button’s value. The last two are the same path. Writing the same path into two components moves it into the cache once for each, but the content is the same and the hash is the same, so they still land in the same directory.

The FileDesk.Write layer does not reference Gradio.NET.

    public static string Write(string text)
    {
        Directory.CreateDirectory(OutputFolder);

        var path = Path.Combine(OutputFolder, "sheet.txt");
        File.WriteAllText(path, text + "\n");

        return path;
    }

It only writes the text into a file and returns the path. Whether the file should be moved into the cache, and where, is the component’s business. The business code does not know the cache exists, so it does not need to change for it.

Figure 12-11 shows it after generation: sheet.txt appears in the manifest file block, 215 bytes, with a download arrow on the right; the download button gets the same value too.

Figure 12-11 Generating the manifest: the file block and the download button both get the same file

Click the download button and the browser saves a 215-byte sheet.txt. This file is byte-for-byte identical to the one in the out directory. The manifest has only four lines (one for each of the three files and a “Total” line at the end), and 215 bytes is the length those characters occupy in UTF-8, not the sum of the three files’ byte counts. The number 1,078 is in the manifest body; it is what the “Total” line writes.

Can the downloaded thing be used again? Yes. Figure 12-12 shows the result of uploading that just-downloaded file back into the single-file block and clicking “Read single”: sheet.txt, 215 bytes, 5 lines, with the first line being the manifest’s first entry.

Figure 12-12 Read again after download: the byte count matches, and so does the content

The download-then-read round trip is worth walking through once. What it confirms is that outbound and inbound files land on disk under the same rules. Writing out lands by content hash, uploading back lands by content hash again, and both times it is the same content, so the byte counts match. There is no encoding conversion in between, no newline normalization, no BOM added or removed.

This round trip brings out one more consequence. If the outbound file is cleaned up in the cache, clicking download again only yields an error page. To let someone still download it two minutes later, copy it into your own directory before then, or turn cleanup off.

12.8 Chapter Summary

The three parameters fileCount, fileTypes, and type decide the contract. fileCount has three modes: single file passes string, multiple files pass string[], and directory also passes string[] (the same route on the server, the difference is in the front-end picker); it also changes the UI along the way. Single file has no delete button; multiple files have handles, byte counts, download, and delete on each row. fileTypes is written into the browser’s picker and rechecked on the front end, stopping anything non-compliant on the spot with a notice, but the server does not recheck, so it governs experience, not correctness. type has two routes: filepath passes a path, binary passes bytes; for the same 438-byte file, the values the two routes pass to the handler function are completely different.

UploadButton and DownloadButton are actions, not containers. The former is one import per click, with the value recorded on the button, and the upload event brings back an array of paths; the latter sends the file its value points at to the browser on a click, and value must exist at construction time — a button built empty cannot be clicked even if a handler function swaps its value in later.

All four knobs are application-level. UploadFolder decides where files land (by default a gradio folder under the system temporary directory, which can be changed to one beside the program), MaxFileSize decides how large they can be (a front-end notice and a server-side 413, two gates), DeleteCache decides how often to clean up (unset means no cleaning), and AllowedPaths decides which other directories the file endpoint may serve (by default only the cache, everything else is 403).

A file lands at <cache directory>\<content hash>\<original file name>. Splitting directories by content hash has the benefits that the same content takes only one slot, addresses cannot be guessed, and “is this the file from this upload” is judged by the directory. The cost is that the path itself means nothing and cannot be used as storage. A file uploaded two minutes ago may already be gone two minutes later, and the value in the block goes empty along with it.

As for events, upload and change both fire on upload, delete fires when one entry is deleted and brings back the array after deletion, and neither clear nor download fires. Clearing fires only change, downloading fires nothing. To keep a log, bind change as the catch-all.

The outbound route is symmetric with the inbound one. The handler function returns a path outside the cache, the component moves it into the cache, then sends the cache address to the front end; the downloaded bytes are identical to the ones written out, and uploading them back to read gives matching byte and line counts.

Up to this chapter the workbench can handle text, tables, charts, audio and video, and files, and can return results to the UI. But every block on the page is “one-shot”. Change the topic and you have to clear it; nothing from the previous round carries over. The next chapter switches to conversation. Messages accumulate, round after round, and the UI has to remember what was said before.