Basic SAP CAP File Handling
Introduction
Here we look at using CAP OData media entities to upload media by using the @Core.MediaType annotation to tell OData that the contains binary content. With this in place and the entity exposed in some service, you can use HTTP PUT requests to perform direct binary uploads.
Original article available here.
Prerequisites
Basic SAP CAP knowledge
Node.js
SAP CAP development tools (
@sap/cds-dk)curl or a browser for testing
CAP Project Setup
Create a new CAP project and install dependencies:
cds init file-integration
cd file-integration
npm installEdit package.json to use sqlite:
{
...
“cds”: {
“requires”: {
“db”: {
“kind”: “sqlite”,
“credentials”: {
“database”: “db.sqlite”
}
}
}
}
}Define the Data Model and Service
Create db/schema.cds:
namespace com.test;
using { managed } from ‘@sap/cds/common’;
entity File : managed {
key ID : UUID;
// The media content field
@Core.MediaType: mediaType
content : LargeBinary;
// The media type field (MIME type)
@Core.IsMediaType
mediaType : String;
// Optional: Additional metadata
fileName : String(255);
fileSize : Integer;
}Here @Core.MediaType indicates that the field content contains the media data. The annotation @Core.IsMediaType indicates the element contains a MIME type. Find out more about these annotations here.
Next, create srv/test-service.cds:
using { com.test as db } from ‘../db/schema’;
service TestService {
entity File as projection on db.File;
}This is all that is required, no custom handlers are needed for basic upload/download functionality.
You can now deploy using cds deployand then start the server using npm run start .
Uploading Files
First create a file entity using the following:
curl -X POST http://localhost:4004/odata/v4/test/File \
-H “Content-Type: application/json” \
-d ‘{
“fileName”: “test.jpg”,
“mediaType”: “image/jpeg”
}’Response:
{
“@odata.context”: “$metadata#File/$entity”,
“ID”: “fc5c795c-11f1-4853-ab91-a2ca6be39b14”,
“createdAt”: “2024-02-16T10:00:00Z”,
“createdBy”: “anonymous”,
“modifiedAt”: “2024-02-16T10:00:00Z”,
“modifiedBy”: “anonymous”,
“fileName”: “my-image.jpg”,
“mediaType”: “image/jpeg”,
“fileSize”: null
}Now we have a file with no content. Using the ID from the you can now upload the binary content as follows:
curl -X PUT “http://localhost:4004/odata/v4/test/File(fc5c795c-11f1-4853-ab91-a2ca6be39b14)/content” \
-H “Content-Type: image/jpeg” \
--data-binary @./test.jpgHere we used a HTTP PUT operation to send the raw binary data, ensuring the Content-Type header matches the mediaType set in the previous call. Take note of the URL format: /File(ID)/content
To access the file, try visiting the following URL in your browser:
http://localhost:4004/odata/v4/test/File(fc5c795c-11f1-4853-ab91-a2ca6be39b14)/contentThe browser will display/download the file with the correct content type, CAP will return the MIME type.


Comments
Post a Comment