---
title: Retrieve Uploaded Files for Preview Using File Names
product: Form Library
description: Learn how to upload files to a server, store their names in the survey results, and enable file previews. View a free demo for JavaScript to learn more.
framework: jQuery
source: https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/jquery
index: https://surveyjs.io/form-library/examples/overview.md
---

# Retrieve Uploaded Files for Preview Using File Names (jQuery)

When respondents attach a file to a survey, this file can be uploaded to a server or stored directly within a JSON object with survey results. The [File Upload](https://surveyjs.io/form-library/examples/file-upload/) demo describes both approaches and shows how to upload a file and store only its URL in survey results. However, if you store file identifiers different from URLs (for instance, file names), file previews are unavailable. This demo explains how to enable file previews when survey results store only file names.

> 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.

## Upload Files to a Server

The steps to upload a file to a server are the same as for the File Upload demo, except that you should save file names instead of URLs on step 2:

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 names 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.

## Enable File Previews

When survey results store file names, a File Upload question cannot retrieve the files to display their previews. To enable the previews in this case, implement `SurveyModel`'s [`onDownloadFile`](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onDownloadFile) event handler. Within this handler, you need to fetch the required file from the server, encode it to a Base64 string, and pass this string as the second argument to the `options.callback` method. This demo uses the <a href="https://developer.mozilla.org/ru/docs/Web/API/FileReader" target="_blank">FileReader API</a> to encode files.

## 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.

## 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/index.css`

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

### `src/index.js`

```js
import $ from "jquery";
import { Model } from "survey-core";
import "survey-js-ui";
import "survey-core/survey-core.min.css";
import "./index.css";
import { json } from "./json";

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: data[file.name]
                    };
                })
            );
        })
        .catch((error) => {
            console.error("Error: ", error);
            options.callback([], [ "An error occurred during file upload." ]);
        });
});

survey.onDownloadFile.add((_, options) => {
    fetch("https://api.surveyjs.io/private/Surveys/getTempFile?name=" + options.content)
        .then((response) => response.blob())
        .then((blob) => {
            const file = new File([blob], options.fileValue.name, {
                type: options.fileValue.type
            });
            const reader = new FileReader();
            reader.onload = (e) => {
                options.callback("success", e.target.result);
            };
            reader.readAsDataURL(file);
        })
        .catch((error) => {
            console.error("Error: ", error);
            options.callback("error");
        });
});
async function deleteFile(fileURL) {
    try {
        const apiUrl = `https://api.surveyjs.io/private/Surveys/deleteTempFile?name=${encodeURIComponent(fileURL)}`;
        const response = await fetch(apiUrl, { method: "DELETE" });

        if (response.status === 200) {
            console.log(`File ${fileURL} was deleted successfully`);
            return "success";
        } else {
            console.error(`Failed to delete file: ${fileURL}`);
            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");
    }
});

$("#surveyElement").Survey({ model: survey });
```

### `src/json.js`

```js
export const json = {
  "elements": [
    {
      "type": "file",
      "title": "Please upload your photo",
      "name": "photo",
      "acceptedTypes": "image/*",
      "storeDataAsText": false,
      "waitForUpload": true,
      "maxSize": 512000
    }
  ]
};
```

### `src/theme.js`

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

### `package.json`

```json
{
  "dependencies": {
    "jquery": "latest",
    "survey-core": "latest",
    "survey-js-ui": "latest"
  }
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/angular.md)
- [React](https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/reactjs.md)
- [Vue 3](https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/vue3js.md)
- [Vanilla JS](https://surveyjs.io/form-library/examples/store-file-names-in-survey-results/vanillajs.md)
