CAP | FE v4 | 파일 업로드
Fiori Elements v4 List Report에서 CSV를 CAP 서비스로 일괄 업로드: 사용자 정의 액션, 검증, 단일 트랜잭션 삽입.
6분 분량sap · cap · fiori-elements · ui5
CSV 파일의 데이터를 CAP 서비스로 일괄 업로드하고, 이를 사용자 정의 액션으로 Fiori Elements v4 List Report에서 실행하는 엔드투엔드 예제입니다.
참고 저장소 (전체 코드): https://github.com/GonzaloMB/cap-file-uploader-v2.git
요구사항
- CAP (Node.js)
@sap/cds@^8 - 개발 DB: SQLite (
@cap-js/sqlite) 또는 운영 환경의 HANA - FE v4 앱 (List Report + Object Page)
- UI5 1.134.x
데이터 모델 (db/schema.cds)
업로드한 항목을 저장할 간단한 엔티티입니다.
namespace my.bookshop;
entity Books {
key ID : Integer;
title : String;
stock : Integer;
}서비스 + 액션 (srv/cat-service.cds)
Books를 노출하고, CSV 행을 타입이 지정된 입력으로 받는 액션을 추가합니다.
using my.bookshop as my from '../db/schema';
type BooksInput { title: String; stock: Integer; }
service CatalogService {
entity Books as projection on my.Books;
action UploadBooks(items: array of BooksInput) returns Integer;
}구현 (srv/cat-service.js): 검증 + 단일 트랜잭션 일괄 삽입.
const cds = require("@sap/cds");
module.exports = cds.service.impl(async function () {
const { Books } = this.entities;
this.on("UploadBooks", async (req) => {
const { items } = req.data;
if (!Array.isArray(items) || items.length === 0)
return req.error(400, "No records were provided");
items.forEach((item, i) => {
if (typeof item.title !== "string" || item.title.trim().length < 3)
req.error(400, `Row ${i + 1}: invalid 'title'`);
if (!Number.isInteger(item.stock) || item.stock < 0)
req.error(400, `Row ${i + 1}: invalid 'stock'`);
});
const titles = items.map((i) => i.title.trim().toLowerCase());
const dup = titles.filter((t, i) => titles.indexOf(t) !== i);
if (dup.length)
return req.error(
400,
`Duplicate titles found: ${[...new Set(dup)].join(", ")}`
);
const tx = cds.transaction(req);
await tx.run(
INSERT.into(Books).entries(
items.map((i) => ({
title: i.title.trim(),
stock: i.stock,
IsActiveEntity: true,
}))
)
);
return items.length;
});
});FE v4 앱 (List Report)
manifest에서 List Report 툴바에 사용자 정의 액션을 추가하고 컨트롤러 확장을 연결합니다.
"targets": {
"BooksList": {
"type": "Component",
"id": "BooksList",
"name": "sap.fe.templates.ListReport",
"options": {
"settings": {
"contextPath": "/Books",
"controlConfiguration": {
"@com.sap.vocabularies.UI.v1.LineItem": {
"tableSettings": { "type": "ResponsiveTable" },
"actions": {
"customAction": {
"press": ".extension.bookstockcontrolv2.ext.controller.ListReportExt.onUploadCSV",
"text": "Upload File",
"requiresSelection": false
}
}
}
}
}
}
}
}어노테이션(app/book_stock_control_v2/annotations.cds)은 필드와 facet을 정의하며, 초안은 @odata.draft.enabled로 켭니다.
UI: 대화 상자 + 컨트롤러 확장
FileUploader와 액션이 있는 대화 상자 프래그먼트입니다.
<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:u="sap.ui.unified">
<Dialog title="{i18n>titleDialogCSV}">
<endButton><Button text="{i18n>btnClose}" type="Negative" press=".onCloseDialog"/></endButton>
<beginButton><Button type="Success" icon="sap-icon://upload" text="{i18n>btnUpload}" press=".onUploadData"/></beginButton>
<VBox alignItems="Center">
<u:FileUploader change="handleFiles" buttonText="{i18n>btnBrowse}" fileType="CSV" placeholder="{i18n>msgNonFileSelect}"/>
<Button type="Neutral" icon="sap-icon://download" text="{i18n>btnDowloadTmpl}" press=".onDownloadTemplate"/>
<MessageStrip id="messageStripId" visible="false" text="{i18n>msgStrip}" type="Success" showIcon="true"/>
</VBox>
</Dialog>
</core:FragmentDefinition>컨트롤러 확장: CSV(세미콜론 구분)를 파싱하고, CAP 액션을 호출하고, 결과를 보여 줍니다.
onUploadCSV() { Fragment.load({ id: this.base.getView().getId(), name: "bookstockcontrolv2.ext.view.UploadFileDialog", controller: this })
.then(d => (this.pDialog = d, this.base.getView().addDependent(d), d.open())); },
handleFiles(oEvent) {
const f = oEvent.getParameter("files")[0];
const r = new FileReader();
r.onload = (e) => {
const rows = e.target.result.split(/\r\n|\n/).map(l => l.split(";")).filter(a => a.length > 1);
const headers = rows.shift();
this.oFileData = rows.map(cols => headers.reduce((o,h,i)=>(o[h]=cols[i],o),{}));
this.base.byId("messageStripId")?.setVisible(true);
};
r.readAsText(f);
},
async onUploadData() {
const oModel = this.base.getView().getModel();
const items = (this.oFileData||[]).map(i => ({ title: i.title, stock: parseInt(i.stock,10) }));
if (!items.length) return MessageToast.show(this._i18n("msgNonFileSelect"));
const res = await fetch(`${oModel.sServiceUrl}UploadBooks`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ items })});
const data = await res.json();
if (!res.ok) throw new Error(data?.error?.message || 'Upload failed');
MessageToast.show(`Created ${data} books.`);
this.onCloseDialog();
}CSV 템플릿 생성도 포함되어 있습니다.
onDownloadTemplate() {
const a = document.createElement('a');
a.href = 'data:text/csv;charset=utf-8,' + encodeURI('title;stock');
a.download = 'TemplateCsv.csv';
a.click();
}CSV 규약
- 구분자: 세미콜론
; - 헤더 행 필수:
title;stock - 검증 규칙 (서비스에서 적용):
title: 문자열, 최소 길이 3, 비어 있지 않음stock: 정수, >= 0- 한 번의 업로드 안에서 제목 중복 없음
실행하고 확인하기
npm install(처음 한 번)cds watch- FE 앱(List Report)을 엽니다. "Upload File" 클릭 → CSV 선택 → Upload.
- 성공 토스트에 생성된 개수가 표시되고, 목록이 자동으로 새로고침됩니다.
문제 해결
- 백엔드 메시지와 함께 400: 문제가 된 행을 고치세요 (제목 최소 길이, 정수 재고, 중복).
- 빈 업로드: CSV에 헤더가 있고 구분자가
;인지 확인하세요. - 대화 상자가 열리지 않음:
manifest.json의 컨트롤러 확장 경로를 확인하세요. - 초안 엔티티 플래그: FE v4에서 바로 보이도록 삽입 시
IsActiveEntity: true를 설정합니다.