---
title: File Upload
product: Form Library
description: Learn how to add a file upload question to your survey or form and handle the storage of uploaded files. You can save them in a JSON object with survey results as Base64 URL strings or upload them to the server separately from the rest of the received data. View a free demo for JavaScript to learn more.
framework: React
source: https://surveyjs.io/form-library/examples/file-upload/reactjs
index: https://surveyjs.io/form-library/examples/overview.md
---

# File Upload (React)

File Upload questions enable respondents to easily upload images, documents, multimedia, and other file types without relying on external file sharing services. Users can simply drag and drop or select a single or multiple files directly within the survey interface to upload relevant information. Files can be uploaded to a server or stored directly in the survey results JSON object. This demo shows how to upload files to a server but describes both storage methods.

> In this demo, files are uploaded to SurveyJS servers from where they are then deleted after a predefined period of time. We strongly encourage you to use your own servers for file uploads when you use SurveyJS to collect sensitive respondent data in your application.

## Store Files as Base64 URLs vs Upload Files to a Server

A File Upload question can manage files in two different ways:

- Store files as Base64 URLs    
Files are encoded to Base64 strings that are stored directly within a JSON object with survey results.

- Upload files to a server    
Files are stored on a server, while the JSON object with survey results contains only unique file identifiers (file names or URLs).

The following sections describe both approaches and help you decide which approach meets your needs best.

### Store Files as Base64 URLs

The Base64 format represents binary data as printable text. A File Upload question encodes uploaded files to Base64 strings and stores them in `SurveyModel`'s [`data`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#data) object. When users complete a survey, the `data` object is saved along with the Base64-encoded files to your database.

This approach allows you to easily retrieve files when you retrieve survey data, but it significantly increases the size of a JSON object with survey results. If you want to store uploaded files separately from survey results, set a File Upload question's [`storeDataAsText`](https://surveyjs.io/form-library/documentation/api-reference/file-model#storeDataAsText) property to `false` and follow the instructions from the next section to implement an event handler that uploads files to a server.

### Upload Files to a Server

To decrease the size of a JSON object with survey results, upload files to a server. In this case, the survey results will contain only unique identifiers (file names or URLs) associated with the uploaded files. To implement this functionality, follow the steps below:

1. Disable the [`storeDataAsText`](https://surveyjs.io/form-library/documentation/api-reference/file-model#storeDataAsText) property for the File Upload question.
2. Use `SurveyModel`'s [`onUploadFiles`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onUploadFiles) event to upload files and save file URLs in survey results.      
Within the event handler, call the `options.callback` function when file upload ends. Pass an array of successfully uploaded files as the first argument. As the second argument, you can pass an array of error messages if file upload failed.
3. Enable the File Upload question's [`waitForUpload`](https://surveyjs.io/form-library/documentation/api-reference/file-model#waitForUpload) property to ensure that users won't complete the survey until files are uploaded.

If you save file URLs on step 2, a File Upload question automatically displays a preview of uploaded files because they can be accessed by a URL. If you use a different file identifier (for example, a file name), file previews won't be available. In this case, you can handle `SurveyModel`'s [`onDownloadFile`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onDownloadFile) event to fetch the uploaded files and display their previews. Refer to the [Retrieve Uploaded Files for Preview Using File Names](https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/) demo for more information.

### Remove Files from a Server

Users can click an individual file's Remove button to delete this file or click the Clear button to delete all uploaded files. Handle `SurveyModel`'s [`onClearFiles`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onClearFiles) event to delete the files from a server storage.

Within an `onClearFiles` event handler, you can identify the file to delete using the `options.fileName` parameter. Send a request to your server to delete the specified file. If `options.fileName` contains `null`, it means that the user has clicked the Clear button to delete all uploaded files. In this case, you should send a request to delete files listed in the `options.value` array.

Once you receive a response from the server, call the `options.callback` method. Pass `"success"` or `"error"` to indicate the operation status. As the second argument, you can pass deleted files' data (`options.value`) if file deletion was successful or an error message if file deletion failed.

## Limit the File Size

Respondents can upload files of any size unless you set a File Upload question's [`maxSize`](https://surveyjs.io/form-library/documentation/api-reference/file-model#maxSize) property. This property accepts a number that specifies maximum allowed file size in bytes. If this size is exceeded, the File Upload question displays an error message. You can handle the [`onValidateQuestion`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onValidateQuestion) event to customize the error message text. In this demo, the maximum file size is set to 100 KB.

## Upload Multiple Files

A File Upload question allows respondents to upload more than one file simultaneously. To enable this feature, set the question's [`allowMultiple`](https://surveyjs.io/form-library/documentation/api-reference/file-model#allowMultiple) property to `true`. You can then set the [`maxFiles`](https://surveyjs.io/form-library/documentation/api-reference/file-model#maxFiles) property to control how many files users are allowed to upload. By default, the maximum number of files is 1000. In this demo, it is set to 5.

## Files

### `public/index.html`

```html
<div id="surveyElement" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; min-height: 100%; height:100%"></div>
```

### `src/SurveyComponent.jsx`

```js
import React from "react";
import { Model } from "survey-core";
import { Survey } from "survey-react-ui";
import "survey-core/survey-core.min.css";
import "./index.css";
import { json } from "./json";

function SurveyComponent() {
    const survey = new Model(json);
    survey.onComplete.add((sender, options) => {
        console.log(JSON.stringify(sender.data, null, 3));
    });
    survey.onUploadFiles.add((_, options) => {
        const formData = new FormData();
        options.files.forEach((file) => {
            formData.append(file.name, file);
        });
    
        fetch("https://api.surveyjs.io/private/Surveys/uploadTempFiles", {
            method: "POST",
            body: formData
        })
            .then((response) => response.json())
            .then((data) => {
                options.callback(
                    options.files.map((file) => {
                        return {
                            file: file,
                            content: "https://api.surveyjs.io/private/Surveys/getTempFile?name=" + data[file.name]
                        };
                    })
                );
            })
            .catch((error) => {
                console.error("Error: ", error);
                options.callback([], [ 'An error occurred during file upload.' ]);
            });
    });
    
    async function deleteFile(fileURL) {
        try {
            const name = fileURL.split("=")[1];
            const apiUrl = `https://api.surveyjs.io/private/Surveys/deleteTempFile?name=${name}`;
            const response = await fetch(apiUrl, { method: "DELETE" });
    
            if (response.status === 200) {
                console.log(`File ${name} was deleted successfully`);
                return "success";
            } else {
                console.error(`Failed to delete file: ${name}`);
                return "error";
            }
        } catch (error) {
            console.error("Error while deleting file: ", error);
            return "error";
        }
    }
    
    survey.onClearFiles.add(async (_, options) => {
        if (!options.value || options.value.length === 0) {
            return options.callback("success");
        }
    
        const filesToDelete = options.fileName
            ? options.value.filter((item) => item.name === options.fileName)
            : options.value;
    
        if (filesToDelete.length === 0) {
            console.error(`File with name ${options.fileName} is not found`);
            return options.callback("error");
        }
    
        const results = await Promise.all(
            filesToDelete.map((file) => deleteFile(file.content))
        );
    
        if (results.every((res) => res === "success")) {
            options.callback("success");
        } else {
            options.callback("error");
        }
    });
    return (<Survey model={survey} />);
}

export default SurveyComponent;
```

### `src/index.css`

```css
/* You can add your custom CSS here. */
```

### `src/index.js`

```js
import React from "react";
import { createRoot } from "react-dom/client";
import SurveyComponent from "./SurveyComponent";

const root = createRoot(document.getElementById("surveyElement"));
root.render(<SurveyComponent />);
```

### `src/json.js`

```js
export const json = {
  "elements": [
    {
      "type": "file",
      "title": "Please upload your files",
      "name": "files",
      "storeDataAsText": false,
      "waitForUpload": true,
      "allowMultiple": true,
      "maxSize": 102400,
      "maxFiles": 5
    }
  ]
};
```

### `src/theme.js`

```js
export const themeJson = {};
```

### `package.json`

```json
{
  "dependencies": {
    "react": "latest",
    "react-dom": "latest",
    "survey-core": "latest",
    "survey-react-ui": "latest"
  },
  "devDependencies": {
    "react-scripts": "latest"
  }
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/form-library/examples/file-upload/angular.md)
- [Vue 3](https://surveyjs.io/form-library/examples/file-upload/vue3js.md)
- [jQuery](https://surveyjs.io/form-library/examples/file-upload/jquery.md)
- [Vanilla JS](https://surveyjs.io/form-library/examples/file-upload/vanillajs.md)
