> Markdown version of [Upload and Download Files](https://vaadin.com/docs/next/building-apps/react/upload-download). Section index: [llms.txt](https://vaadin.com/docs/next/building-apps/llms.txt)

# Upload and Download Files

This guide shows how to upload files from a React view with the [Upload](https://vaadin.com/docs/next/components/upload.md) component, and how to let users download them. Both go through a Spring controller: the Upload component sends each file in a request of its own, and a browser downloads a file from a URL.

## <a id="creating-the-controller"></a>Creating the Controller

Create a Spring controller with one method that receives an uploaded file, and one that sends a file back. The following controller keeps the files in memory and gives each one an ID:

`FileController.java`

`FileController.java`

```java
@RestController
@RequestMapping("/api/files")
public class FileController {

    record StoredFile(String name, MediaType type, byte[] content) {
    }

    // Keeps the files in memory. Use a database or a file store instead.
    private final Map<String, StoredFile> files = new ConcurrentHashMap<>();

    @PostMapping
    public String upload(@RequestParam("file") MultipartFile file)
            throws IOException {
        var type = file.getContentType() == null
                ? MediaType.APPLICATION_OCTET_STREAM
                : MediaType.parseMediaType(file.getContentType());
        var id = UUID.randomUUID().toString();
        files.put(id, new StoredFile(file.getOriginalFilename(), type,
                file.getBytes()));
        return id;
    }

    @GetMapping("/{id}")
    public ResponseEntity<byte[]> download(@PathVariable String id) {
        var file = files.get(id);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        var disposition = ContentDisposition.attachment()
                .filename(file.name(), StandardCharsets.UTF_8).build();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
                .contentType(file.type()).body(file.content());
    }
}
```

The `upload()` method returns the ID of the file as the response text. The `download()` method sends the file with a `Content-Disposition` header, which makes the browser save it under its original name. `ContentDisposition` encodes names that contain other than ASCII characters.

Keep the controller’s path apart from the routes of your views, for example under `/api`. That way, the security rule for the controller doesn’t apply to a view.

## <a id="allowing-access-to-the-controller"></a>Allowing Access to the Controller

Vaadin’s security configuration denies the requests that no rule allows, so add a rule for the controller. The following rule lets logged-in users upload and download files:

```java
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/files/**").authenticated());
    http.with(VaadinSecurityConfigurer.vaadin(), configurer -> {
        configurer.loginView("/login");
    });
    return http.build();
}
```

For the other options, see [Security Configuration](https://vaadin.com/docs/next/flow/security/spring/security-configuration.md) in the reference.

## <a id="uploading-files"></a>Uploading Files

Point the `target` of the Upload component to the controller, and send the files as multipart form data. By default, the component sends the raw content of the file, which a `MultipartFile` parameter doesn’t accept. The following view uploads files, and lists the uploaded files with links for downloading them:

`views/files.tsx`

`files-view.tsx`

```tsx
type StoredFile = { id: string; name: string };

export default function FilesView() {
  const files = useSignal<StoredFile[]>([]);

  return (
    <>
      <Upload
        target="api/files"
        uploadFormat="multipart"
        onUploadRequest={(event) => addCsrfHeader(event.detail.xhr)}
        onUploadSuccess={(event) => {
          const { file, xhr } = event.detail;
          files.value = [...files.value, { id: xhr.responseText, name: file.name }];
        }}
      />
      <ul>
        {files.value.map((file) => (
          <li key={file.id}>
            <a href={`api/files/${file.id}`} download>
              {file.name}
            </a>
          </li>
        ))}
      </ul>
    </>
  );
}
```

Spring Security rejects a `POST` request without a CSRF token. Vaadin adds the token to the page in `<meta>` tags, and the `onUploadRequest` handler copies it to each upload request:

`files-view.tsx`

```tsx
// Adds the CSRF token that Spring Security expects
function addCsrfHeader(xhr: XMLHttpRequest) {
  const header = document.querySelector<HTMLMetaElement>('meta[name="_csrf_header"]')?.content;
  const token = document.querySelector<HTMLMetaElement>('meta[name="_csrf"]')?.content;
  if (header && token) {
    xhr.setRequestHeader(header, token);
  }
}
```

The handler reads the token for each request, because the token changes when the user logs in.

When the upload succeeds, `xhr.responseText` holds the response of the controller, here the ID of the file. The view keeps the ID and the name of each uploaded file in a signal.

### <a id="limiting-the-file-size"></a>Limiting the File Size

Spring Boot accepts files of up to 1 MB by default. For a larger file, the server answers with status 413, and the Upload component shows that the file is too large. To accept larger files, set the limits in `application.properties`:

```properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
```

To reject a large file before it’s uploaded, also set the `maxFileSize` property of the Upload component, in bytes.

## <a id="downloading-files"></a>Downloading Files

To let users download a file, link to the download URL of the controller, and add the `download` attribute to the link. The view above does this for each uploaded file:

`files-view.tsx`

```tsx
<ul>
  {files.value.map((file) => (
    <li key={file.id}>
      <a href={`api/files/${file.id}`} download>
        {file.name}
      </a>
    </li>
  ))}
</ul>
```

The router ignores links that have the `download` attribute, so the browser downloads the file instead of opening a view.
