Skip to main content
Version: 3.1

File Upload

Technical reference for the FileUpload module in Care EMR. For what a file is in Care and how people work with files, read the Files concept.

Source:

A FileUpload record holds the metadata of one file. The content of the file is in object storage, in the patient-files bucket, not in the database.

Each record links to one patient, encounter, consent, diagnostic report, service request or referral through file_type and associating_id. There is no database foreign key to that record.

The Django model is the storage layer. It stores the row and the meta JSON column that it gets from its base model.

The Pydantic resource specs are the API layer. They define the file_type and file_category enums, validate a create, put mime_type into meta, and shape every response.

extension, signed_url and read_signed_url are computed when a record is serialized. They have no columns.

Models​

ModelPurpose
FileUploadMetadata record for one file in object storage, linked to another Care record by file_type and associating_id

FileUpload extends EMRBaseModel, which adds history, meta, created_by and updated_by.

EMRBaseModel extends BaseModel, which adds external_id, created_date, modified_date and the soft-delete flag deleted. Care sets the two dates automatically.

FileUpload fields​

File metadata​

FieldTypeNotes
nameCharField(2000)Display name. Required in the API (FileUploadBaseSpec.name). The only field that an update can change
internal_nameCharField(2000)Storage object name. Create copies original_name into it, then save() replaces it with a random name plus the last extension. Not in the create or update schema
associating_idCharField(100), blank=False, null=FalseThe external_id of the linked record. No database ForeignKey: the authorization check looks the record up
file_typeCharField(100)Kind of linked record. The API limits it to FileTypeChoices
file_categoryCharField(100)The API limits it to FileCategoryChoices
upload_completedBooleanField, default FalseSet to True by mark_upload_completed, or at once by upload-file. The list returns only rows where it is True

Archival​

FieldTypeNotes
is_archivedBooleanField, default FalseSet to True by the archive action. A separate field from the soft-delete flag deleted
archive_reasonTextField, blank=TrueSet from the archive request body
archived_datetimeDateTimeField, nullableSet to the current date and time when the file is archived
archived_byForeignKey to User (PROTECT), nullable, related_name="archived_files"The user who archived the file

meta JSON contents​

meta is the JSONField from EMRBaseModel. The file specs store one key in it.

KeyTypeNotes
mime_typestrWritten on create from the request's mime_type. Read back into the mime_type response field. On upload-file, Care detects it from the content

Responses never include meta itself, because EMRResource.to_json() drops it.

Storage manager​

FileUpload declares a class-level files_manager = S3FilesManager(BucketType.PATIENT). It is not a database field. It creates the signed URLs and runs put_object against the patient-files bucket.

Enum values​

FileTypeChoices values​

String enum in spec.py. The value decides which authorization check runs. See Authorization.

ValueLinks a file toNotes
patientA patientcare_fe lists these files in the patient Files tab
encounterAn encountercare_fe lists these files in the encounter Files tab. care_fe questionnaire file answers also use this type
consentA consentcare_fe consent uploads use this type with the category consent_attachment
diagnostic_reportA diagnostic reportcare_fe diagnostic report attachments use this type
service_requestA service requestChecked with the service request permissions
referralA referralcare_fe referral uploads use this type

The care_fe Files tab supports only the patient and encounter types.

FileCategoryChoices values​

String enum in spec.py.

ValueNotes
audio—
xray—
identity_proof—
unspecifiedcare_fe Files tab uploads and questionnaire file answers use this category
discharge_summary—
consent_attachmentThe consent read schemas embed the consent files that have this category

FileUpload links to User through these foreign keys.

FieldRelated modelNotes
archived_byUserPROTECT, nullable, related_name="archived_files"
created_byUserFrom EMRBaseModel. The uploaded_by response field shows this user
updated_byUserFrom EMRBaseModel

Resource specs (API schema)​

Every spec extends EMRResource, which sets __store_metadata__ = False by default. The file specs write and read meta["mime_type"] in their own hooks.

SpecRoleFields and behaviour
FileUploadBaseSpecshared baseid: UUID4 | None, name: str (required)
FileUploadCreateSpecwrite · createAdds required original_name, file_type, file_category, associating_id: str and mime_type: str. Validates mime_type and original_name. On deserialize, sets _just_created=True, copies original_name into internal_name, and stores meta["mime_type"]
FileUploadUpdateSpecwrite · updateAdds nothing to the base, so an update can change only name
FileUploadListSpecread · listSee read fields. Also the response of mark_upload_completed and archive
FileUploadRetrieveSpecread · detailAdds signed_url, read_signed_url and internal_name. Returns a write URL when _just_created is set, else a read URL
ConsentFileUploadCreateSpecnot usedDefined, but no endpoint uses it. It takes original_name and associating_id: UUID4, sets file_type=consent and file_category=consent_attachment, and does not set meta["mime_type"]

Consent files are created like every other file, with FileUploadCreateSpec. care_fe consent uploads use the signed-URL flow with file_type=consent and file_category=consent_attachment.

FileUploadCreateSpec validation​

FieldRule and error message
nameRequired, from the base spec
original_nameMust not be empty: File name cannot be empty
original_nameAt most 255 characters: File name cannot exceed 255 characters.
original_nameMust not start with a dot: File name cannot start with a dot.
original_nameMust have an extension: Invalid file extension.
original_nameThe last extension must not be in BLOCKED_FILE_EXTENSIONS: File extension not allowed. Blocked extensions are: followed by the list
original_nameThe last extension must be in ALLOWED_FILE_EXTENSIONS: File extension not allowed. Allowed extensions are: followed by the list
mime_typeMust be in ALLOWED_MIME_TYPES: Invalid mime type
file_typeMust be a FileTypeChoices value
file_categoryMust be a FileCategoryChoices value
associating_idRequired str. The authorization check looks up the record by this external_id

The extension checks look only at the last extension. For scan.tar.gz, they check gz.

FileUploadListSpec read fields​

FieldTypeSource
idUUID4obj.external_id
namestrcolumn
file_typeFileTypeChoicescolumn
file_categoryFileCategoryChoicescolumn
associating_idstrcolumn
upload_completedboolcolumn
is_archivedbool | Nonecolumn
archive_reasonstr | Nonecolumn
archived_datetimedatetime | Nonecolumn
created_datedatetimecolumn
extensionstrobj.get_extension()
mime_typestrobj.meta.get("mime_type")
uploaded_bydict | NoneUserSpec from cache, for obj.created_by_id
archived_byUserSpec | NoneUserSpec from cache, for obj.archived_by_id
created_by, updated_bydict | NoneAudit users

FileUploadRetrieveSpec extra fields​

FieldTypeWhen set
signed_urlstr | NoneWhen _just_created is set, which is the create response. A write (PUT) URL from files_manager.signed_url(obj)
read_signed_urlstr | NoneIn every other FileUploadRetrieveSpec response. A read (GET) URL from files_manager.read_signed_url(obj)
internal_namestrThe storage object name

Server-maintained behaviour​

  • Clients cannot set internal_name. The create and update schemas do not have it, and save() generates it.
  • On create, Care stores the declared mime_type as the client sends it. On upload-file, Care detects it from the content.
  • uploaded_by is the user who created the record. Any user who passes the write check can call mark_upload_completed, not only the uploader.
  • The archive action sets is_archived, archive_reason, archived_datetime and archived_by.
  • The archive action accepts any archive_reason string, also an empty one.
  • The archive action does not check is_archived or upload_completed. Archiving an archived file again overwrites archive_reason, archived_datetime and archived_by.
  • The update endpoint does not check is_archived, so the API accepts a new name for an archived file.
  • Validation errors return HTTP 400 with an errors list. Each item has a msg.

Methods & save behaviour​

get_extension()​

Returns the last extension of internal_name with a leading dot, such as .pdf, or "" when there is none.

It calls parse_file_extension with the default max_extensions=1, so a name that ends in .tar.gz gives .gz.

The extension response field and the file name in the read URL use it.

save() side effects​

save() sets a random internal_name when the row is new or internal_name is empty, unless the caller passes skip_internal_name=True.

  1. Care builds a random name: uuid4() followed by the current Unix time.
  2. If get_extension() finds an extension on the current internal_name, Care appends it. On create, that is the last extension of original_name.
  3. Care stores the result in internal_name before it saves the row.

The save() docstring says that the random name avoids leaking PII if data leaks. No field keeps the original file name.

upload-file saves the record a second time with skip_internal_name=True, so the random name from the first save stays.

API integration notes​

Every request needs a signed-in user.

Endpoints​

The base path is /api/v1/files/. In each path, {id} is the id that the API returns for the file, which is its external_id.

ActionMethod and pathCheckBodyResponse
listGET /api/v1/files/read on the query's file_type and associating_idNone. Query parameters, see ListPaged FileUploadListSpec items. Only rows with upload_completed=True
createPOST /api/v1/files/write on the body's file_type and associating_idFileUploadCreateSpecFileUploadRetrieveSpec with signed_url
retrieveGET /api/v1/files/{id}/readNoneFileUploadRetrieveSpec with read_signed_url
updatePUT /api/v1/files/{id}/writeFileUploadUpdateSpec (name)FileUploadRetrieveSpec with read_signed_url
mark_upload_completedPOST /api/v1/files/{id}/mark_upload_completed/writeNoneFileUploadListSpec
archivePOST /api/v1/files/{id}/archive/writearchive_reason: str, requiredFileUploadListSpec
upload-filePOST /api/v1/files/upload-file/write, as for createoriginal_name, base64 file_data, name, file_type, file_category, associating_idFileUploadRetrieveSpec with read_signed_url

There is no DELETE route and no action to unarchive a file. The viewset has only the create, retrieve, update and list mixins, plus three extra actions.

Retrieve, update, mark_upload_completed and archive look the file up among all records. So they also find uploads that are not complete.

List​

A list request names one record with the file_type and associating_id query parameters.

A request with neither parameter fails with Cannot filter files. With only one, the authorization check runs with the other value empty, and the request fails with Cannot View File or as not found.

ParameterBehaviour
file_typeExact match. Also selects the authorization check
associating_idExact match on the linked record's external_id
is_archivedBoolean. Without it, the list returns archived and active files together
file_categoryOne or more categories, separated by commas
nameCase-insensitive match on any part of name
orderingcreated_date or modified_date. A leading - reverses the order: care_fe sends -created_date for newest first. Without the parameter, the newest records come first

The list uses limit and offset pagination, 14 items per page by default.

Upload flows​

Signed-URL upload. The care_fe Files tab uses this flow.

  1. Send POST /api/v1/files/ with a FileUploadCreateSpec. The response carries signed_url, a write URL.
  2. Send the file content with PUT to signed_url within one hour, with the content type that you declared in mime_type. The server does not check the size of this upload.
  3. Send POST /api/v1/files/{id}/mark_upload_completed/. The file then appears in the list.

If step 3 does not happen, the file stays out of the list. The cleanup task deletes it later, unless FILE_UPLOAD_EXPIRY_HOURS is 0. See Incomplete-upload cleanup.

Inline upload. POST /api/v1/files/upload-file/ sends the file content in one request. care_fe sends answers to a questionnaire "files" question this way, as encounter files with the category unspecified.

  1. The server decodes the base64 file_data and checks its size against MAX_FILE_UPLOAD_SIZE.
  2. The server detects the MIME type from the first 2048 bytes and checks it against ALLOWED_MIME_TYPES.
  3. The server builds a FileUploadCreateSpec from the body and the detected mime_type, so the original_name checks of create also apply.
  4. In one transaction, the server runs the create check, saves the record, puts the object in storage and sets upload_completed=True.
  5. If the storage write fails, nothing is saved.

The response is a FileUploadRetrieveSpec with read_signed_url, because upload-file sets _just_created=False.

upload-file errorMessage
original_name or file_data is missingMissing required fields: 'original_name' or 'file_data'
file_data is not valid base64Invalid base64-encoded file data
The content is larger than MAX_FILE_UPLOAD_SIZE megabytesFile size exceeds the limit of 5.0MB with the default. The number follows the setting
MIME type detection failsError detecting file type.
The detected MIME type is not allowedFile type '<type>' is not allowed
The storage write failsFailed to upload file to storage

Authorization​

Every endpoint calls file_authorizer(user, file_type, associating_id, action), where the action is "read" or "write". The Endpoints table shows which.

The check that runs depends on file_type. Roles and their permissions are stored in the database, so the role lists below are defaults.

file_typeCheckPasses whenDefault roles
patientreadHandler can_view_clinical_data on the patient. The user holds can_view_clinical_data ("Can view clinical data about patients") in one of their roles on the patientStaff, Doctor, Nurse, Facility Admin
patientwriteHandler can_write_patient_obj on the patient. The user holds can_write_patient ("Can Update a Patient's data") in one of their roles on the patient. If PATIENT_GLOBAL_EDIT_ACCESS_ENABLED is on, a role with that permission in any facility organization or organization also countsStaff, Doctor, Nurse, Administrator, Facility Admin
encounterreadEither the patient read check, on the encounter's patient, or handler can_view_encounter_clinical_data on the encounter. The second passes when the user holds can_read_encounter_clinical_data ("Can Read encounter related clinical data") in the encounter's facility organizations or its current location's organizations. The second check does not look at the encounter status. The first check takes roles only from encounters that are not closed, so it can stop passing when this encounter closesPatient check: as for patient. Encounter check: Doctor, Nurse, Facility Admin
encounterwriteHandler can_update_encounter_clinical_data on the encounter. Refused for every user when the encounter is closed. Otherwise, the user holds can_write_encounter_clinical_data ("Update Encounter related clinical data") in the encounter's facility organizations or its current location's organizationsDoctor, Nurse, Facility Admin
consentread, writeThe encounter checks, run on the consent's encounter, with the same status rules. A closed encounter blocks writesAs for encounter
diagnostic_reportreadHandler can_read_diagnostic_report on the report's service request. The user holds can_read_diagnostic_report ("Can Read Diagnostic Report") in a facility organization of the service request's encounter or its current location, or of the service request's locations. No encounter status checkFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer
diagnostic_reportwriteHandler can_write_diagnostic_report on the report's service request. The user holds can_write_diagnostic_report ("Can Create Diagnostic Report on Facility") in the same places as for read. No encounter status checkFacility Admin, Doctor, Nurse
service_requestreadHandler can_read_service_request. The user holds can_read_service_request ("Can Read Service Request") in the same places as for diagnostic_report. No encounter status checkFacility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist
service_requestwriteHandler can_write_service_request. The user holds can_write_service_request ("Can Write Service Request on Facility") in the same places. No encounter status checkFacility Admin, Doctor, Nurse
referralreadHandler can_read_referral. The user holds can_read_referral ("Can Read Referrals") at the referral's origin or at its destinationAdministrator, Doctor, Facility Admin, Nurse, Staff, and the Admin, Manager and Member roles of a role organization
referralwriteHandler can_write_referral. The user holds can_write_referral ("Can Update Referrals") at the referral's origin or at its destinationAs for read

Where the roles must be held:

  • A user's roles on a patient include their roles in the facility organizations of each encounter of the patient that is not closed. This includes the organizations of that encounter's current location.
  • They also include the user's roles in the organizations whose ids are in the patient's organization cache, and a role given to the user directly on the patient.
  • The cache holds the patient's geographic organization and its parents. For each organization linked to the patient, it also holds that organization's parents and the id of the link row.
  • So a closed encounter no longer gives the user roles on the patient.
  • An encounter is closed when its status is completed, cancelled, entered_in_error or discontinued (COMPLETED_CHOICES). The labels are "Completed", "Cancelled", "Entered in error" and "Discontinued".
  • Other statuses, such as Discharged, On Hold and In Progress, are not closed.
  • A permission checked in a set of organizations passes only when the user holds a role with that permission in one of them.
  • At the referral's origin, the permission must be held in a facility organization of the referral's encounter or its current location. If the referral has no encounter, it must be in one of the user's roles on the patient.
  • At the referral's destination, if the destination is an organization, the permission must be held in that organization or one of its parents.
  • If the destination is a facility, the permission must be held in that facility's root organization.
  • The patient checks do not look at the patient's own status, such as deceased.

When a check fails:

  • When no check passes, or file_type is not a known value, the request fails with PermissionDenied and the message Cannot View File. The same message applies to read and write checks.
  • When the linked record does not exist, the request fails with HTTP 404 and No <Model> matches the given query.

Role notes:

  • The permission definitions also name an Admin role. Roles are matched by name, and the only role named Admin in the database is for role organizations, which the facility screens do not offer. The table above leaves it out, except as the Admin role of a role organization for referral.
  • By default, Administrator holds can_write_patient but not can_view_clinical_data. So it passes the write check for patient files and fails the read check.
  • By default, Staff passes the write check for patient files but not for encounter or consent files.

Signed URLs and storage​

  • The object key is {file_type}/{internal_name}, in the bucket that FILE_UPLOAD_BUCKET names.
  • The write URL (signed_url) is a PUT URL. It expires after 3600 seconds and carries the stored mime_type as ContentType, so storage accepts the upload only with that content type.
  • The read URL (read_signed_url) is a GET URL. It expires after 3600 seconds.
  • The read URL sets Content-Disposition to inline for the types in SAFE_INLINE_FORMATS and to attachment for every other type. The file name is name followed by extension.
  • SAFE_INLINE_FORMATS are image/jpeg, image/png, image/gif, image/webp, image/tiff, image/bmp, image/x-icon and application/pdf.
  • The patient-files bucket client uses the FACILITY_S3_KEY, FACILITY_S3_SECRET and FACILITY_S3_REGION settings. It does not read FILE_UPLOAD_KEY, FILE_UPLOAD_SECRET or FILE_UPLOAD_REGION, which are also defined.

Settings​

A deployment can change each of these settings.

SettingDefaultUsed by
ALLOWED_FILE_EXTENSIONSjpg, jpeg, png, gif, bmp, webp, svg, mp4, mpeg, avi, mov, wmv, flv, webm, mp3, wav, aac, ogg, midi, mid, m4a, txt, csv, rtf, doc, odt, pdf, xls, xlsx, odsThe original_name check on create and on upload-file
BLOCKED_FILE_EXTENSIONSexe, dll, msi, msp, mst, com, scr, sys, pif, reg, bat, cmd, wsf, shThe original_name check on create and on upload-file
ALLOWED_MIME_TYPESimage/jpeg, image/png, image/gif, image/bmp, image/webp, image/svg+xml, video/mp4, video/mpeg, video/x-msvideo, video/quicktime, video/x-ms-wmv, video/x-flv, video/webm, audio/mpeg, audio/wav, audio/aac, audio/ogg, audio/midi, audio/x-midi, audio/webm, audio/mp4, text/plain, text/csv, application/rtf, application/msword, application/vnd.oasis.opendocument.text, application/pdf, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.oasis.opendocument.spreadsheetThe mime_type check on create, and the detected type on upload-file
MAX_FILE_UPLOAD_SIZE5 (megabytes)The size check in upload-file, and nowhere else. The signed-URL upload has no server-side size check
FILE_UPLOAD_EXPIRY_HOURS24. 0 turns the cleanup offThe age limit and the run interval of the cleanup task
PATIENT_GLOBAL_EDIT_ACCESS_ENABLEDFalseThe patient write check

The default lists accept the Word doc format (application/msword) but not docx.

Incomplete-upload cleanup​

  • The task cleanup_incomplete_file_uploads hard-deletes every FileUpload with upload_completed=False that was created more than FILE_UPLOAD_EXPIRY_HOURS hours ago.
  • It deletes the storage object first, then the database rows.
  • It runs every FILE_UPLOAD_EXPIRY_HOURS hours when that setting is not 0. So an incomplete upload can stay for up to about twice that time.

Use by other modules​

  • Consent: the consent read schemas embed source_attachments. These are the files with file_type=consent, file_category=consent_attachment and the consent's external_id as associating_id. This query does not filter on is_archived or upload_completed.
  • Referral: an existing file can be attached to a referral only if it belongs to the referral's patient. Its upload must be complete, and it must not be archived. Otherwise the error is File is not an available file for this patient.
  • Resource references: another resource can reference a file with the resource type file_upload. Reading such a reference runs the read check.
  • Diagnostic report templates list the report's files that are not archived.
  • User profile pictures and facility cover images do not use FileUpload. They are stored directly in the facility bucket.