> Markdown version of [Downloads](https://vaadin.com/docs/next/flow/advanced/downloads). Section index: [llms.txt](https://vaadin.com/docs/next/flow/llms.txt)

# Handle Downloads

The `DownloadHandler` API provides a flexible high-level abstraction to implement file and arbitrary contents downloads from server to browser in Vaadin applications. This API supports various download scenarios, from simple file downloads to complex streaming with progress tracking.

`DownloadHandler` is supported by multiple Vaadin components where applicable.

This documentation covers the main features of the `DownloadHandler` API, including:

- [Common download scenarios](#common)

- [Starting a download from a component click](#onclick)

- [Opening content in a new tab](#new-tab)

- [Creating custom download handlers](#custom)

- [Download progress tracking](#progress)

- [Transfer lifecycle](#lifecycle)

- [Low-level API features](#low-level)

## <a id="common"></a>Common Download Scenarios

The `DownloadHandler` can be in a form of lambda, where you can control the data transfer and UI updates thanks to `DownloadEvent` API, or can use several provided static helper methods to simplify common download scenarios.

### <a id="using-downloadevent-and-lambda-expression"></a>Using DownloadEvent And Lambda Expression

The `DownloadHandler` is a `FunctionalInterface` and can be created using a lambda expression:

```java
Anchor downloadLink = new Anchor((DownloadEvent event) -> {
    event.fileName("readme.md");
    var anchor = event.getOwningComponent();
    event.getResponse().setHeader("Cache-Control", "public, max-age=3600");
    try (OutputStream outputStream = event.getOutputStream()) {
        // Write data to the output stream
    }
    event.getUI().access(() -> { /* UI updates */});
}, "Download me!");
```

Using `DownloadEvent` and lambda is particularly useful for:

- Writing arbitrary data to the response output stream

- Setting file meta-data like file name, content type, and content length

- Update UI or owner component during the download, with `UI.access()`

- Having access to the `VaadinRequest`, `VaadinResponse`, and `VaadinSession` instances

### <a id="ui-state"></a>Reading UI State in a Download Handler

The browser requests the download in a request of its own, apart from the requests of the UI. Vaadin calls the handler for that request without holding the session lock. This applies to every `DownloadHandler`, including the callback of `fromInputStream`.

The `DownloadEvent` gives access to the session, the UI, and the owner component, but the lock isn’t held while the handler uses them. Reading the value of a UI component in the handler races with the requests of the UI that change it. Changing the UI needs `UI.access()`, as in the example above.

When the content depends on what the user sees, such as the filter of a grid, copy the values that the handler needs in a listener. Listeners run while holding the lock. The handler then reads the copy:

```java
AtomicReference<String> filter = new AtomicReference<>("");
TextField filterField = new TextField("Filter");
filterField.addValueChangeListener(e -> filter.set(e.getValue()));

Anchor export = new Anchor(DownloadHandler.fromInputStream(event -> {
    try {
        byte[] csv = reportService.exportCsv(filter.get());
        return new DownloadResponse(new ByteArrayInputStream(csv),
                "report.csv", "text/csv", csv.length);
    } catch (Exception e) {
        return DownloadResponse.error(500, e);
    }
}), "Export");
```

The copy holds the last value that the server has received. An `Anchor` or `Download.onClick()` starts the download on the click, without waiting for a server round trip. A value that the user has typed last may reach the server only after that, for example when a `TextField` sends its value on blur. For content that the browser loads by itself, such as the data of an `HtmlObject`, you can create the handler in a server-side click listener instead, as in the dynamic image example in [Custom Download Handler Examples](#custom-examples).

### <a id="errors"></a>Handling Errors in a Download Handler

Catch exceptions inside the handler and return `DownloadResponse.error()`, as the example above does. The browser then gets a response with that status code. An exception that the handler throws goes to the error handler of the session and then to the servlet container, which answers with its own error response.

In neither case does the UI show that the download failed. The handlers that the `DownloadHandler` factory methods create notify their progress listeners of the failure in both cases, so a `whenComplete()` listener can tell the user — see [Download Progress Listeners](#progress).

### <a id="download-content-from-inputstream"></a>Download Content from InputStream

The `fromInputStream` method allows you to serve content from any `InputStream`. This is the most flexible helper method as it can be used with any data source that can provide an `InputStream`.

`InputStreamDownloadView.java`

```java
Anchor downloadAttachment = new Anchor(
                DownloadHandler.fromInputStream((event) -> {
                    try {
                        Attachment attachment = attachmentsRepository
                                .findById(attachmentId);
                        return new DownloadResponse(
                                attachment.getData().getBinaryStream(),
                                attachment.getName(), attachment.getMime(),
                                attachment.getSize());
                    } catch (Exception e) {
                        return DownloadResponse.error(500);
                    }
                }), "Download attachment");
```

This method is particularly useful for:

- Serving content from databases or file storage

- Generating dynamic content

- Streaming large files

By default, the returned handler doesn’t answer byte range requests, which media players use to seek and which Safari requires before it plays audio or video at all. Call `enableRangeRequests()` to opt in, but only when the callback returns the same content, with a known content length, on every call — see [Byte Range Requests](#byte-ranges). (V25.4 pre-release)

#### <a id="overriding-the-file-name"></a>Overriding the File Name (since V25.2)

By default, the file name of the download comes from the `DownloadResponse` returned by the callback, and the download URL is a random-looking string. The `fromInputStream` overload that takes a `fileNameOverride` parameter lets you define the file name already when the handler is created:

```java
Anchor downloadLink = new Anchor(DownloadHandler.fromInputStream(event -> {
    byte[] report = reportService.generateReport();
    return new DownloadResponse(new ByteArrayInputStream(report),
            event.getFileName(), "application/pdf", report.length);
}, "monthly-report.pdf"), "Download Monthly Report");
```

The given file name is appended to the download URL as a postfix (see [URL Postfix](#url-postfix)), and `getFileName()` of the `DownloadEvent` returns it inside the callback, as shown above. This is useful when serving generated content under a stable, user-friendly file name, without writing a custom download handler. An overload that additionally accepts a `TransferProgressListener` is also available.

### <a id="render-or-download-static-resource"></a>Render Or Download Static Resource

The `forClassResource` and `forServletResource` methods allows you to serve resources from the classpath or servlet context. For instance, for the file `src/main/resources/com/example/ui/vaadin.jpeg` and class `com.example.ui.MainView` the code would be:

```java
Image logoImage = new Image(DownloadHandler.forClassResource(
        MainView.class, "vaadin.jpeg"), "Vaadin Logo");
```

This method is useful for serving static resources like images, templates, fonts, and other types of files that are packaged with your application.

If the resource name starts with `/`, it will then look from `/src/main/resources` without the class path prepended.

By default, these handlers don’t answer byte range requests, which media players use to seek and which Safari requires before it plays audio or video at all. Call `enableRangeRequests()` on the handler to opt in: (V25.4 pre-release)

```java
Video video = new Video();
video.addSource(DownloadHandler.forClassResource(MyView.class, "intro.mp4")
        .enableRangeRequests(), "video/mp4");
```

See [Byte Range Requests](#byte-ranges) for when this is safe and what it costs.

### <a id="download-a-file-from-file-system"></a>Download A File From File System

The `forFile` method allows you to serve files from the server’s file system.

```java
Anchor download = new Anchor(DownloadHandler.forFile(new File("/path/to/terms-and-conditions.md")), "Download Terms and Conditions");
```

This method is useful for serving files that are stored on the server’s file system.

Unlike the other factory methods, it also answers byte range requests by default, by seeking in the file — see [Byte Range Requests](#byte-ranges) — which makes it the recommended way to serve large media. (V25.4 pre-release)

The `Anchor` component sets the `download` attribute by default and download handlers extending `AbstractDownloadHandler` also set the `Content-Disposition` to `attachment`. If the content should be inlined to the page, this have to be set explicitly by calling the `inline()` method on the `DownloadHandler` instance and using `AttachmentType.INLINE`:

```java
Anchor download = new Anchor(DownloadHandler.forFile(new File("/path/to/terms-and-conditions.md")).inline(), AttachmentType.INLINE, "View Terms and Conditions");
```

### <a id="setting-the-content-type"></a>Setting the Content Type (V25.4 pre-release)

By default, `forFile`, `forClassResource`, `forServletResource`, and `fromInputStream` handlers take the content type from the MIME type that the servlet container maps to the file name, falling back to `application/octet-stream` for an extension it doesn’t map. The `withContentType` method sets the content type explicitly instead, which is useful for file types the servlet container doesn’t recognize, such as `.vtt` subtitle files:

```java
Anchor download = new Anchor(DownloadHandler.forFile(new File("captions.vtt")).withContentType("text/vtt"), "Download Captions");
```

A content type that a `DownloadResponse` gives for a particular download still takes precedence over the one set with `withContentType`, as it’s the more specific one. The `getContentType` method returns the type set with `withContentType`, or `null` if none was set.

The built-in handlers apply the type set with `withContentType` themselves. A custom handler that extends `AbstractDownloadHandler` and sets the content type of its own response should take it from `resolveContentType(String, VaadinResponse)`, which returns the type set with `withContentType`, or else the type the servlet container maps to the given file name:

```java
@Override
public void handleDownloadRequest(DownloadEvent downloadEvent) {
    downloadEvent.setContentType(
            resolveContentType("report.csv", downloadEvent.getResponse()));
    // write the response...
}
```

## <a id="onclick"></a>Starting a Download From a Component Click (V25.4 pre-release)

The examples above bind a `DownloadHandler` to an `Anchor`, which renders a regular link and lets the browser handle the download natively. `Download.onClick` starts a download from a click on a `Button` or any other component — so the component keeps its own look, keyboard handling, and click listeners instead of being wrapped in a link:

```java
Button export = new Button("Export");
Download.onClick(export, DownloadHandler.fromInputStream(event -> {
    byte[] report = reportService.createReport();
    return new DownloadResponse(new ByteArrayInputStream(report),
            "report.pdf", "application/pdf", report.length);
}));
```

The download starts in the browser’s own click handler, inside the user gesture, without waiting for a server round trip. The handler itself still runs on the server, but only once the browser requests the file — so the file name and response headers can be decided at that point, as with any `DownloadHandler`.

This saves the content as a file: a handler that only gives a file name, with `DownloadEvent.fileName(String)`, is served as an attachment, but a handler that calls `DownloadEvent.inline()` itself keeps that choice. To show the content in a new browser tab instead, pass `DownloadTarget.NEW_TAB` as a third argument, as described in [Opening Content in a New Tab](#new-tab).

`Download.onClick` also accepts a URL the browser can already address, optionally with a suggested file name:

```java
Download.onClick(export, "/files/report.pdf");
Download.onClick(export, "/files/report.pdf", "report.pdf");
```

Browsers use the suggested file name only for same-origin URLs; for other URLs the server has to send the name in a `Content-Disposition` header instead.

The handler is served only while the component is attached, visible, and enabled. If a button disables itself on click, the browser may still request the file after the component is disabled; call `allowDisabled()` on the handler to serve it in that case. It returns a handler with the `ALWAYS` [disabled update mode](#low-level):

```java
Download.onClick(export,
        DownloadHandler.fromInputStream(event -> ...).allowDisabled());
```

`onClick` returns a `Registration`. Calling `remove()` on it removes the click listener and, for a handler-based download, unregisters the handler so its URL stops serving the file.

## <a id="new-tab"></a>Opening Content in a New Tab (V25.4 pre-release)

Pass `DownloadTarget.NEW_TAB` as a third argument to `Download.onClick` to show the content of a `DownloadHandler`, or a URL, in a new browser tab when a button or any other clickable component is clicked, instead of downloading it:

```java
Button view = new Button("View invoice");
Download.onClick(view, DownloadHandler.fromInputStream(event -> {
    byte[] pdf = invoiceService.createPdf();
    return new DownloadResponse(new ByteArrayInputStream(pdf), "invoice.pdf",
            "application/pdf", pdf.length);
}), DownloadTarget.NEW_TAB);
```

As with [`Download.onClick` without a target](#onclick), the new tab opens in the browser’s own click handler, without waiting for a server round trip, so popup blockers let it through. Opening a tab from a server-side click listener, for example with `Page.open`, happens only after the round trip and may be blocked. The new tab opens without access to the opening page (`noopener`) and without a `Referer` header (`noreferrer`).

The handler runs only when the new tab requests the content, once per click, and the browser shows it when it can, for example a PDF, an image, or plain text. A handler that only gives a file name, with `DownloadEvent.fileName(String)`, is served inline for this use; a handler that calls `DownloadEvent.attachment(String)` itself keeps that choice instead. The handler itself is not changed, so the same instance can also be used where the content is downloaded, such as in an `Anchor` or in [`Download.onClick` without a target](#onclick).

The handler follows the clicked component’s lifecycle in the same way as without a target, including `allowDisabled()` for a button that disables itself on click:

```java
Download.onClick(button, DownloadHandler.forFile(file).allowDisabled(),
        DownloadTarget.NEW_TAB);
```

`Download.onClick` also accepts a URL directly, for content the browser can already address, such as a static file, an application route, or an external page:

```java
Download.onClick(helpButton, "https://example.com/help", DownloadTarget.NEW_TAB);
```

Both overloads return a `Registration` for removing the behavior from the component; after removal, the handler or URL is no longer opened on click.

## <a id="custom"></a>Custom Download Handlers

For more complex download scenarios, you can create custom download handlers by implementing the `DownloadHandler` interface or extending existing implementations.

Creating an implementation is needed only when overriding some of the default methods from the interface, e.g. `getUrlPostfix`, `isAllowInert` or `getDisabledUpdateMode`:

```java
Anchor downloadLink = new Anchor(new DownloadHandler() {
    @Override
    public void handleDownloadRequest(DownloadEvent event) {
        // Custom download handling logic
    }

    @Override
    public String getUrlPostfix() {
        return "custom-download.txt";
    }
}, "Download me!");
```

### <a id="custom-examples"></a>Custom Download Handler Examples

Here’s an example of how a custom download handler can be written with lambda. It adds a header to the response, write data to `OutputStream`, updates the UI, and tracks the number of downloads per session:

```java
String filename = getFileName();
String contentType = getContentType();
AtomicInteger numberOfDownloads = new AtomicInteger(0);
Anchor link = new Anchor(event -> {
    try {
        event.fileName(filename);
        event.setContentType(contentType);
        byte[] data = loadFileFromS3(filename, contentType);
        event.getResponse().setHeader("Cache-Control", "public, max-age=3600");
        event.getOutputStream().write(data);
        // Remember to enable @Push
        // Use event.getUI().push() if push is manual
        event.getUI().access(() -> Notification.show(
                "Download completed, number of downloads: " +
                    numberOfDownloads.incrementAndGet()));
        event.getSession().lock();
        try {
            event.getSession().setAttribute("downloads-number-" + fileName,
                    numberOfDownloads.get());
        } finally {
            event.getSession().unlock();
        }
    } catch (IOException e) {
        event.getResponse().setStatus(500);
    }
}, "Download from S3");

private byte[] loadFileFromS3(String fileName, String contentType) {
    byte[] bytes = new byte[1024 * 1024 * 10]; // 10 MB buffer
    // load from file storage by file name and content type
    return bytes;
}
```

This example shows how to:

- Set file meta-data with helpers in `DownloadEvent`

- Set a header to the response

- Write data directly to the response output stream

- Update the UI after the download completes

- Store download statistics in the session

The `DownloadEvent` gives the access to the following information and helper methods:

- `VaadinRequest`, `VaadinResponse`, `VaadinSession` instances

- `getOutputStream` method to write the download content represented as a stream of bytes to response

- `getWriter` method to write the download content represented as a formatted text to response

- The owner component and element of the download that you can change with `UI.access()` when download is in progress, e.g. disable the component, or get attributes or properties

- `UI` instance that you can use to call `UI.access()` for asynchronous updates

- The helper `fileName` method sets the file name for the download; a `null` or blank value is ignored. Whether the content is then saved or shown depends on where the handler is used, unless the handler calls `attachment` or `inline` itself to decide that explicitly

- The helper `setContentType` method sets the content type for the download

- The helper `setContentLength` method sets the content length for the download or does nothing if the `-1` value is given

> **Note:** The handler runs without the session lock. `UI.access` is needed for updating the UI and also session locking if you want to access the session. See [Reading UI State in a Download Handler](#ui-state).

> **Note:** Methods `getOutputStream` and `getWriter` cannot be used simultaneously for the same response, either one or the other.

Another example is how to generate and render a dynamic content using a `DownloadHandler`.

```java
TextField name = new TextField("Input a name...");
HtmlObject image = new HtmlObject();
image.setType("image/svg+xml");
image.getStyle().set("display", "block");
Button button = new Button("Generate Image", click -> {
    String value = name.getValue();
    image.setData(DownloadHandler.fromInputStream(event -> new DownloadResponse(
            getImageInputStream(value), "image.svg", "image/svg+xml", -1)));
});
```

The `HtmlObject` component is used to render the SVG image in the browser that is generated dynamically based on the input from the `TextField`. On a button click the `DownloadHandler` is created with the `fromInputStream` method that is set to `HtmlObject` component and that sends content to a client. The click listener reads the value of the `TextField`, because the handler runs without the session lock. And here is an example of how to generate a svg image and create an input stream:

```java
private InputStream getImageInputStream(String value) {
    String svg = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>"
        + "<svg xmlns='http://www.w3.org/2000/svg' "
        + "xmlns:xlink='http://www.w3.org/1999/xlink'>"
        + "<rect x='10' y='10' height='100' width='100' "
        + "style=' fill: #90C3D4'/><text x='30' y='30' fill='red'>"
        + value + "</text>" + "</svg>";
    return new ByteArrayInputStream(svg.getBytes(StandardCharsets.UTF_8));
}
```

When `DownloadHandler` is used with `Anchor` component, the data is downloaded as a file. This can be changed to render the data in the browser by using `inline()` method:

```java
Anchor downloadLink = new Anchor(DownloadHandler.fromFile(
        new File("/path/to/document.pdf"), "report.pdf").inline(), "Download Report");
```

The second parameter of the `fromFile` method is the file name that will be used for download. This name is also used as a URL postfix.

Finally, the `DownloadHandler` can be created from an abstract base class `AbstractDownloadHandler`:

```java
public class MyDownloadHandler extends AbstractDownloadHandler<MyDownloadHandler> {
    @Override
    public void handleDownloadRequest(DownloadEvent downloadEvent) {
        byte[] data;
        // load data from backend...
        try (OutputStream outputStream = downloadEvent.getOutputStream();
             ByteArrayInputStream inputStream = new ByteArrayInputStream(data)) {
            TransferUtil.transfer(inputStream, outputStream,
                    getTransferContext(downloadEvent), getListeners());
        } catch (IOException ioe) {
            downloadEvent.getResponse().setStatus(
                    HttpStatusCode.INTERNAL_SERVER_ERROR.getCode());
            notifyError(downloadEvent, ioe);
        }
    }
}
```

This example shows how to:

- Extend the `AbstractDownloadHandler` class

- Override the `handleDownloadRequest` method to implement custom download handling logic

- Use the `TransferUtil` class to transfer data from an `InputStream` to an `OutputStream`. This helper method also fires progress events to the listeners so no need to implement this logic manually, see also [Download progress tracking](#progress)

- Notify progress listeners about errors by calling the `notifyError` method

## <a id="progress"></a>Download Progress Listeners

The `DownloadHandler` API provides two ways to track download progress:

1. Using the fluent API with shorthand methods

2. Implementing the `TransferProgressListener` interface

Asynchronous UI updates in progress listeners are automatically wrapped into `UI.access()` calls by Vaadin, thus you don’t need to call it manually. Vaadin `@Push` should be enabled in your application to be able to see UI updates while download is in progress.

The UI used for the `UI.access` call is the one that was active when the download started. Listeners are also notified for a download that outlives its owner component or its browser tab, as described in [Transfer Lifecycle](#lifecycle).

### <a id="fluent-api-for-progress-tracking"></a>Fluent API for Progress Tracking

The fluent API provides a concise way to track download progress using method chaining.

```java
InputStreamDownloadHandler handler = DownloadHandler.fromInputStream(event ->
        new DownloadResponse(getInputStream(), "download.bin",
            "application/octet-stream", contentSize))
    .whenStart(() -> {
        Notification.show("Download started", 3000, Notification.Position.BOTTOM_START);
        progressBar.setVisible(true);
    })
    .onProgress((transferred, total) -> progressBar.setValue((double) transferred / total))
    .whenComplete(success -> {
        progressBar.setVisible(false);
        if (success) {
            Notification.show("Download completed", 3000, Notification.Position.BOTTOM_START)
                .addThemeVariants(NotificationVariant.SUCCESS);
        } else {
            Notification.show("Download failed", 3000, Notification.Position.BOTTOM_START)
                    .addThemeVariants(NotificationVariant.ERROR);
        }
    });
```

The fluent API provides the following methods:

- `whenStart(Runnable)`: Called when the download starts

- `onProgress(BiConsumer<Long, Long>)`: Called during the download with transferred and total bytes

- `onProgress(BiConsumer<Long, Long>, Long)`: Called during the download with transferred and total bytes and with the given progress interval in bytes

- `whenComplete(Consumer<Boolean>)`: Called when the download completes successfully or with a failure

These methods have overloads that accept also the `TransferContext` object that gives more information and references:

- `VaadinRequest`, `VaadinResponse`, `VaadinSession` instances

- The owner component and element of the data transfer that you can change when transfer is in progress, e.g. disable the component, or get attributes or properties

- `UI` instance that you can use to call `UI.access()` for asynchronous updates in threads

- The name of the file being transferred, might be \<code>null\</code> if the file name is not known

- The content length of the file being transferred, might be \<code>-1\</code> if the content length is not known

### <a id="transferprogresslistener-interface"></a>TransferProgressListener Interface

For more control over download progress tracking, you can implement the `TransferProgressListener` interface.

```java
InputStreamDownloadHandler handler = DownloadHandler.fromInputStream(event ->
        new DownloadResponse(getInputStream(), "download.bin",
            "application/octet-stream", contentSize),
        "download.bin", new TransferProgressListener() {
    @Override
    public void onStart(TransferContext context) {
        Notification.show("Download started for file " + context.fileName(),
                3000, Notification.Position.BOTTOM_START);
        progressBar.setVisible(true);
    }

    @Override
    public void onProgress(TransferContext context, long transferredBytes,
                             long totalBytes) {
        progressBar.setValue((double) transferredBytes / totalBytes);
    }

    @Override
    public void onError(TransferContext context, IOException reason) {
        progressBar.setVisible(false);
        Notification.show("Download failed, reason: " + reason.getMessage(),
                3000, Notification.Position.BOTTOM_START);
    }

    @Override
    public void onComplete(TransferContext context, long transferredBytes) {
        progressBar.setVisible(false);
        Notification.show("Download completed, total bytes " + transferredBytes,
                        3000, Notification.Position.BOTTOM_START);
    }

    @Override
    public long progressReportInterval() {
        return 1024 * 1024 * 2; // 2 MB
    }
});
```

The `TransferProgressListener` interface provides the following methods:

- `onStart(TransferContext)`: Called when the download starts

- `onProgress(TransferContext, long, long)`: Called during the download with transferred and total bytes

- `onError(TransferContext, IOException)`: Called when the download fails with an exception

- `onComplete(TransferContext, long)`: Called when the download completes with the total transferred bytes

- `progressReportInterval()`: Defines how often progress updates are sent (in bytes)

The `TransferContext` objects are the same as in the fluent API.

## <a id="lifecycle"></a>Transfer Lifecycle

A download is served independently of the owner component’s lifecycle. The owner’s attached, visible, enabled, and inert state is checked when the download request is received, but not while the download is being served. Once handling has started, detaching the owner component, navigating to another view, or closing the browser tab doesn’t stop the download on the server. It runs to completion as long as the browser keeps reading the response.

A UI that’s closed while a download for it is ongoing stays attached to its session until the download has completed (V25.4 pre-release). This applies, for example, when the user closes the browser tab, or when the UI is closed because its heartbeats have stopped. Progress listeners bound to that UI are therefore still notified, although their UI changes no longer reach any browser. Once the download has completed, the UI is removed from the session.

A download doesn’t outlive its session (V25.4 pre-release), though. When the session is invalidated, either explicitly or by timing out, the ongoing download is terminated:

- The output stream and the writer of the response stop accepting content and throw an `IOException`.

- The browser receives a truncated file.

- A warning with the request path and the owner component is logged.

This applies to the built-in handlers and to custom handlers that write through the response they receive. Progress listener notifications are skipped once the UI has been removed from the ended session. To let a long download finish regardless, keep the session alive while the download is ongoing. You can also serve the download from a servlet of your own that isn’t tied to a UI or a session.

## <a id="low-level"></a>Low-Level DownloadHandler API

The `DownloadHandler` API provides several low-level features for advanced use cases.

### <a id="inert-property"></a>Inert Property

The `inert` property controls whether the download should be handled when the owner component is in an inert state, e.g. when a modal dialog is opened while the owner component is on the underlined page. See the [Server-Side Modality](https://vaadin.com/docs/next/flow/advanced/server-side-modality.md) for details.

`DownloadHandler` allows to handle download request from inert component by overriding the `isAllowInert()` method.

### <a id="disabled-update-mode"></a>Disabled Update Mode

The `DisabledUpdateMode` controls whether downloads are allowed when the owner component is disabled.

The available modes are:

- `ONLY_WHEN_ENABLED`: Download handling is rejected when the owner component is disabled (default)

- `ALWAYS`: Download handling is allowed even when the owner component is disabled

`DownloadHandler` allows to override this mode by overriding the `getDisabledUpdateMode()` method.

### <a id="url-postfix"></a>URL Postfix

The `getUrlPostfix()` method allows you to specify an optional URL postfix that appends application-controlled string, e.g. the logical name of the target file, to the end of the otherwise random-looking download URL. If defined, requests that would otherwise be servable are still rejected if the postfix is missing or invalid. `DownloadHandler` factory methods have overloads that accept the postfix as a parameter.

This is useful for:

- Providing a meaningful filename into the download handler callback

- Making the download request URL look more user-friendly as otherwise it is a random-looking URL

The request URL looks like when the postfix is set: `/VAADIN/dynamic/resource/0/5298ee8b-9686-4a5a-ae1d-b38c62767d6a/meeting-notes.txt`.

By default, the postfix is not set and the request URL looks like: `/VAADIN/dynamic/resource/0/5298ee8b-9686-4a5a-ae1d-b38c62767d6a`.

```java
Anchor downloadLink = new Anchor(new DownloadHandler() {
    @Override
    public void handleDownloadRequest(DownloadEvent event) {
        // download handling...
    }

    @Override
    public boolean isAllowInert() {
        return true; // default is false
    }

    @Override
    public DisabledUpdateMode getDisabledUpdateMode() {
        return DisabledUpdateMode.ALWAYS; // the default is ONLY_WHEN_ENABLED
    }

    @Override
    public String getUrlPostfix() {
        return "meeting-notes.txt";
    }
}, "Download meeting notes");
```

### <a id="byte-ranges"></a>Byte Range Requests (V25.4 pre-release)

A byte range request asks for part of a response instead of the whole thing. Media players use them to seek, and Safari refuses to play audio or video from a handler that doesn’t answer them. `DownloadHandler.forFile()` always answers them, by seeking in the file. `forClassResource`, `forServletResource`, and `fromInputStream` don’t by default. Call `enableRangeRequests()` on the handler to opt in — for example, when a video is packaged with the application rather than stored as a file on disk:

```java
Video video = new Video();
video.addSource(DownloadHandler.forClassResource(MyView.class, "intro.mp4")
        .enableRangeRequests(), "video/mp4");
```

Enabling it isn’t free or safe for every kind of content these methods can serve:

- A class or servlet resource inside a packaged jar or war is often compressed, so each range re-inflates the bytes before it, which adds up for large media fetched in many small ranges.

- An input stream handler calls its callback again for every range request, so ranges are only correct when the callback returns the same content, with a known content length, every time. A stream that can seek, such as a `FileInputStream`, skips the bytes before a range; other streams read through them instead.

`isRangeRequestsEnabled()` reports whether a given handler answers range requests, which code built on `DownloadHandler` can check before deciding how to serve or render the content.

`C82C3953-6480-493C-A5D6-E397BC072DBA`
