Skip to main content

Upload, Save, and Read Attachments with Blob

Give an asset two attachments: a PDF contract and a PNG cover. Upload each file, save both references with the asset, and return temporary download URLs. Then replace the contract and remove the cover.

This walkthrough uses the Java source preview of BlobReferenceModule and the complete runnable example. Use the source revision and setup below; installing an older published SDK alone will not provide these preview APIs. Other runtime and release information lives in the status page.

Evidence status: The downloadable Java source-preview example was compiled and executed with PostgreSQL/File storage on 2026-11-01. It uses explicit runtime metadata; the KSML declaration is illustrative. Execution receipt.

What you write once, and what you write per feature​

Once for the applicationFor an attachment feature
Install the Blob module with storage, a SQL catalog, a content verifier, and current-user authorization.Declare each attachment field and its allowed formats.
Provision the catalog schema and connect it to the business transaction resource.Expose an upload operation for the intended field.
Connect final response preparation and private cache handling to your response adapter.Assign the completed upload's BlobRef and save the business graph.
Schedule maintenance explicitly.Load the required fields and prepare the response.

The module handles binding checks, content verification, and URL issuance. The example runs as a terminal program with PostgreSQL, local File storage, and its provider's temporary HTTP gateway. No web framework or secure-document module is needed for this task.

Run the example first​

You need Java 21, Maven, and a dedicated PostgreSQL test database. The database user must be able to create and drop schemas. Use test input files: an actual PDF and an actual PNG. The example creates a unique schema and temporary storage and removes them when it exits. It grants one demo actor access to its own scope; replace those demo policies with application authorization when integrating it.

Build and install the preview source dependencies into your local Maven cache:

git clone https://github.com/teaql/teaql-java.git
cd teaql-java
git checkout af59bf4ee6f003f509ce8cc42a5d96bb5dcdb8c3
mvn -pl examples/blob-view-preparation -am install -DskipTests
export TEAQL_JAVA_SOURCE="$PWD"
cd ..

Download AttachmentExample.java and run.sh into the same directory, then enter that directory. Set the test configuration in your shell; keep the password out of command arguments and shell history:

export TEAQL_BLOB_TEST_PG_URL='jdbc:postgresql://127.0.0.1:5432/attachment_demo'
export TEAQL_BLOB_TEST_PG_USER='attachment_demo'
read -r -s -p 'Test database password: ' TEAQL_BLOB_TEST_PG_PASSWORD
printf '\n'
export TEAQL_BLOB_TEST_PG_PASSWORD
export TEAQL_VIEW_PDF='/absolute/path/contract.pdf'
export TEAQL_VIEW_PNG='/absolute/path/cover.png'
bash run.sh

Run these commands in Bash. run.sh resolves the source example's Maven classpath, compiles the downloaded Java file, and runs it. If Maven uses a custom cache or executable, set TEAQL_MAVEN_REPO or MAVEN_BIN consistently with the source build. Put the Java 21 java and javac on PATH.

Expect these application receipts; ordinary logging-library notices may also appear:

PASS upload: PDF contract and PNG cover confirmed
PASS save: two independent fields persist stable Keys
PASS read: two complete URLs retrieve original bytes; entity Keys unchanged
PASS replace: new contract Key; cover preserved
PASS clear and reread: null cover; contract still downloadable
PASS committed presentation failure: saved state remains; retry is a read

The executable checks the downloaded bytes and the values stored in SQL. It does not print the temporary URLs. Execution details and limitations are recorded alongside the example.

Declare the fields​

A model can contain several attachment fields. Each field holds one file and has its own format restrictions. For example, the KSML declaration is:

<asset title="string()"
contract="contract.pdf"
cover="cover.png"/>

contract and cover are ordinary field names. A field named document has no special exclusivity. To allow several formats for one field, use file samples such as contract="contract.pdf|contract.docx": this means one PDF or one DOCX, not two files in the field.

In a generated application, evaluate the model, generate it, and use Assist for its entity APIs. The downloadable runtime example deliberately uses an explicit Asset class and BlobFieldSpec metadata for PDF and PNG, so it can run without a generator workspace. Its execution verifies those runtime fields; the KSML block above is a modeling illustration, not a generation result from this example.

Upload a file for a field​

The example's reusable upload helper is:

private static BlobRef upload(UserContext ctx, String field, String fileName,
Path path, String requestId) throws IOException {
var uploads = ctx.capability(BlobRuntime.class).upload();
var session = uploads.begin(ctx, new BlobFieldTarget("Asset", null, field),
new BlobRuntime.Uploads.FileInfo(fileName, Files.size(path), null), requestId);
try (InputStream content = Files.newInputStream(path)) {
uploads.write(ctx, session.uploadId(), content);
}
return uploads.complete(ctx, session.uploadId());
}

begin checks the target field and creates an upload session. write streams the bytes. complete verifies the actual file and returns a bindable BlobRef. A supplied filename or Content-Type is a hint; it does not replace verification.

The null target ID allows an upload before the new asset has an ID. For an existing asset, pass its ID when beginning that upload. Keep entity and field selection under the endpoint's control and apply current-user permissions. Reuse the request ID when retrying the same upload request; choose a new one for a replacement or another upload with different parameters.

BlobRef contract = upload(ctx, "contract", "contract.pdf", pdf, "contract-upload-1");
BlobRef cover = upload(ctx, "cover", "cover.png", png, "cover-upload-1");

Your HTTP upload endpoint can return reference.key() as JSON. The upload is complete but remains unbound until a business save succeeds. An abandoned upload is handled by the configured unbound-retention and maintenance policy.

Save both attachments with the business object​

The example assigns an ID explicitly for its isolated demo row. Use your application's normal creation and ID allocation in a generated application. Here runtime is the configured TeaQLRuntime, and ctx is its trusted current UserContext:

var asset = new Asset();
asset.__internalInitializeNewEntityId(42L);
asset.updateProperty("title", "Supplier agreement");
asset.updateProperty("contract", contract);
asset.updateProperty("cover", cover);
asset.setComment("Create asset with contract and cover");
runtime.saveGraph(ctx, asset);

An endpoint receiving a completed upload Key can parse it with BlobRef.of(key). Parsing checks the reference shape; the save still checks current authorization, target compatibility, and the file's bindable state.

The business columns contain the stable Keys. Binding changes join the same physical SQL transaction as the business graph. You do not manually insert a binding row or call storage from the business save. A failed business transaction does not publish the new binding; the uploaded file can remain for retry or later collection.

Return a view with download URLs​

After the save transaction commits, prepare the response:

PreparedView prepared = runtime.prepareView(
ctx, Map.of("data", asset), ViewOptions.afterCommit());

The response adapter serializes prepared.value() and applies the prepared view's private cache and expiry constraints. Its default cache policy is private, no-store. A schematic response is:

{
"data": {
"id": 42,
"title": "Supplier agreement",
"contract": "https://files.example/read/temporary-contract-credential",
"cover": "https://files.example/read/temporary-cover-credential"
}
}

Those addresses illustrate the response shape; real URLs come complete from the configured provider. The application does not build a URL prefix. The actual entity and SQL columns still hold BlobRef Keys.

For a subsequent GET, load the asset with the attachment fields you need, then use ViewOptions.readOnly() instead. Preparation only visits already-loaded, visible fields. It does not load omitted fields for you. The example checks this read-only preparation path after removing the cover; it is not a demonstration of a generated query API.

Call preparation after any caller-owned transaction has completed. If business work committed but signing fails, the failure retains the committed outcome: re-read the object and retry presentation rather than replaying the mutation.

Replace or clear an attachment​

Upload the replacement first, then save its new reference:

BlobRef replacement = upload(ctx, "contract", "replacement.pdf", pdf,
"contract-upload-2");
asset.updateProperty("contract", replacement);
asset.setComment("Replace supplier contract");
runtime.saveGraph(ctx, asset);

The cover stays unchanged. Even identical replacement bytes get a new upload reference in this example. Clear the nullable cover field with:

asset.updateProperty("cover", null);
asset.setComment("Remove cover attachment");
runtime.saveGraph(ctx, asset);

Clearing a field removes its binding. Physical deletion follows retention and a maintenance check that no active binding remains. The example validates the saved fields and download behavior; it does not run the garbage collector.

Add an attachment list​

For an arbitrary number of files, model a child collection: each attachment row has a single Blob field plus business attributes such as display name, sort order, or a note. Fixed roles such as contract and cover can stay as separate fields on the asset. A multi-format declaration alone does not create a list.

Refresh a download and choose your authorization boundary​

When a URL expires, request the currently authorized business view again. There is no need to upload or replace the file. A normal signed URL can be transferred and used until its expiry; removing permission after issuance does not promise immediate revocation of that URL. If every download must recheck the current user, select a provider or gateway with that explicit read capability.

Ordinary attachments use the Blob module alone. The optional secure-document module adds protected business editing and file-selection credentials; uploading a PDF or PNG does not itself require that module. Its separate role and runtime availability are described in the reference status.