Retrieve Uploaded Files for Preview Using File Names
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 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:
- Disable the
storeDataAsText
property for the File Upload question. - Use
SurveyModel
'sonUploadFiles
event to upload files and save file names in survey results.
Within the event handler, call theoptions.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. - Enable the File Upload question's
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
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 FileReader API 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
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.