namespace Media.db;
entity MediaFile {
key id : Integer;
@Core.MediaType : mediaType
content : LargeBinary;
@Core.IsMediaType : true
mediaType : String;
fileName : String;
url : String;
};
using {Media.db as db} from '../db/data-model';
service MediaService @(path : '/media') {
entity MediaFile as projection on db.MediaFile;
};
const SequenceHelper = require("./library/SequenceHelper");
const { Readable, PassThrough } = require("stream");
const cds = require('@sap/cds');
cds.env.features.fetch_csrf = true
module.exports = cds.service.impl(async function () {
const {
MediaFile
} = this.entities;
/**
* Handler method called before creating data entry
* for entity Mediafile.
*/
this.before('CREATE', MediaFile, async (req) => {
const db = await cds.connect.to("db");
// Create Constructor for SequenceHelper
// Pass the sequence name and db
const SeqReq = new SequenceHelper({
sequence: "MEDIA_ID",
db: db,
});
//Call method getNextNumber() to fetch the next sequence number
let seq_no = await SeqReq.getNextNumber();
// Assign the sequence number to id element
req.data.id = seq_no;
//Assign the url by appending the id
req.data.url = `/media/MediaFile(${req.data.id})/content`;
});
/**
* Handler method called on reading data entry
* for entity Mediafile.
**/
this.on("READ", MediaFile, async (req, next) => {
if (!req.data.id) {
return next();
}
//Fetch the url from where the req is triggered
const url = req._.req.path;
//If the request url contains keyword "content"
// then read the media content
if (url.includes("content")) {
const id = req.data.id;
var tx = cds.transaction(req);
// Fetch the media obj from database
var mediaObj = await tx.run(
SELECT.one.from("Media.db.MediaFile", ["content", "mediaType"]).where(
"id =",
id
)
);
if (mediaObj.length <= 0) {
req.reject(404, "Media not found for the ID");
return;
}
var decodedMedia = "";
decodedMedia = new Buffer.from(
mediaObj.content.toString().split(";base64,").pop(),
"base64"
);
return _formatResult(decodedMedia, mediaObj.mediaType);
} else return next();
});
function _formatResult(decodedMedia, mediaType) {
const readable = new Readable();
const result = new Array();
readable.push(decodedMedia);
readable.push(null);
return {
value: readable,
'*@odata.mediaContentType': mediaType
}
}
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:u="sap.ui.unified" controllerName="com.ta.mediaui.controller.mediaUpload" displayBlock="true">
<Shell id="shell">
<App id="app">
<pages>
<Page id="page" title="{i18n>title}">
<content>
<FlexBox direction="Column" class="sapUiLargeMargin">
<Label text="Attach File" labelFor="fileUploader" required="true"/>
<u:FileUploader id="__fileUploader" tooltip="Upload your file to DB" change="onFileChange"/>
<Button text="Upload" press="onUploadFile" type="Emphasized"/>
<Image ariaDetails="detailsActiveImage" src="media_srv/v2/media/MediaFile(1)/content"
decorative="false"/>
</FlexBox>
</content>
</Page>
</pages>
</App>
</Shell>
</mvc:View>
// @ts-nocheck
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageBox"
],
/**
* @param {typeof sap.ui.core.mvc.Controller} Controller
*/
function (Controller, MessageBox) {
"use strict";
return Controller.extend("com.ta.mediaui.controller.mediaUpload", {
onInit: function () {
},
_getBaseURL: function () {
var oBaseUrl = this.getOwnerComponent().getManifestEntry("/sap.app/id").replaceAll(".", "/");
return jQuery.sap.getModulePath(oBaseUrl)
},
/**
* on File Change
*/
onFileChange: function (oEvent) {
var file = oEvent.getParameters("files").files[0];
this.file = file;
},
/**
* On File Upload
*/
onUploadFile: function () {
var oUploadSet = this.byId("__fileUploader");
//Upload image
var reader = new FileReader();
reader.onload = function (oEvent) {
// get an access to the content of the file
this.content = oEvent.currentTarget.result;
this.createfile();
}.bind(this);
reader.readAsDataURL(this.file);
},
/**
* Create Operation to create an entry in CAP
*/
createfile: function () {
var that = this;
// Data for CAP to create entry
var oImageData = {
"content": this.content,
"mediaType": this.file.type,
"fileName": this.file.name
};
var oCAPModel = this.getOwnerComponent().getModel("oCAPModel");
var sURL = "/MediaFile";
//Create call for CAP OData Service
oCAPModel.create(sURL, oImageData, {
success: function (oData, oResponse) {
var id = oData.id;
var sMsg = "File Uploaded Successfully for ID: " + id;
MessageBox.success(sMsg);
},
error: function (jqXHR, textStatus) {
},
});
},
});
});
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
11 | |
10 | |
10 | |
9 | |
8 | |
8 | |
6 | |
6 | |
5 | |
5 |