π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
working upload attachment
Fendy Heryanto4328570d2071
diff --git a/packages/nocodb/src/controllers/v3/data-v3.controller.ts b/packages/nocodb/src/controllers/v3/data-v3.controller.tsindex a511e5ad03..b015f78af7 100644--- a/packages/nocodb/src/controllers/v3/data-v3.controller.ts+++ b/packages/nocodb/src/controllers/v3/data-v3.controller.ts@@ -28,6 +28,7 @@ import { TenantContext } from '~/decorators/tenant-context.decorator';import { NcContext, NcRequest } from '~/interface/config';import { DataV3Service } from '~/services/v3/data-v3.service';import { DataTableService } from '~/services/data-table.service';+import { DataAttachmentV3Service } from '~/services/v3/data-attachment-v3.service';import { PREFIX_APIV3_DATA } from '~/constants/controllers';@Controller()@@ -36,6 +37,7 @@ export class Datav3Controller {constructor(protected readonly dataV3Service: DataV3Service,protected readonly dataTableService: DataTableService,+ protected readonly dataAttachmentV3Service: DataAttachmentV3Service,) {}@Get(`${PREFIX_APIV3_DATA}/:modelId/records`)@@ -79,6 +81,28 @@ export class Datav3Controller {});}+ @Post(+ `${PREFIX_APIV3_DATA}/:modelId/records/:recordId/columns/:columnId/upload`,+ )+ @HttpCode(200)+ @Acl('dataUpdate')+ async dataAttachmentUpload(+ @TenantContext() context: NcContext,+ @Param('modelId') modelId: string,+ @Param('recordId') recordId: string,+ @Param('columnId') columnId: string,+ @Body() body: { contentType: string; file: string; filename: string },+ ) {+ return await this.dataAttachmentV3Service.appendBase64AttachmentToCellData({+ context,+ modelId,+ recordId,+ columnId,+ scope: undefined,+ attachment: body,+ });+ }+@Delete(`${PREFIX_APIV3_DATA}/:modelId/records`)@Acl('dataDelete')async dataDelete(@@ -218,7 +242,6 @@ export class Datav3Controller {res.json(countResult);}-@Get(`${PREFIX_APIV3_DATA}/:modelId/records/:rowId`)@Acl('dataRead')async dataRead(diff --git a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts b/packages/nocodb/src/services/v3/data-attachment-v3.service.tsindex 104abe1263..40d0ed61b0 100644--- a/packages/nocodb/src/services/v3/data-attachment-v3.service.ts+++ b/packages/nocodb/src/services/v3/data-attachment-v3.service.ts@@ -4,7 +4,12 @@ import { forwardRef, Inject, Injectable } from '@nestjs/common';import axios from 'axios';import { nanoid } from 'nanoid';import slash from 'slash';-import type { AttachmentUrlUploadParam } from '~/types/data-columns/attachment';+import { NcError } from 'src/helpers/ncError';+import { DataV3Service } from './data-v3.service';+import type {+ AttachmentBase64UploadParam,+ AttachmentUrlUploadParam,+} from '~/types/data-columns/attachment';import {NC_ATTACHMENT_FIELD_SIZE,NC_ATTACHMENT_URL_MAX_REDIRECT,@@ -28,6 +33,7 @@ export class DataAttachmentV3Service {constructor(@Inject(forwardRef(() => 'JobsService'))private readonly jobsService: IJobsService,+ private readonly dataV3Service: DataV3Service,) {}async handleUrlUploadCellUpdate(param: AttachmentUrlUploadParam) {const { context, modelId, column, recordId, scope, attachments } = param;@@ -110,6 +116,130 @@ export class DataAttachmentV3Service {}}+ async appendBase64AttachmentToCellData(param: AttachmentBase64UploadParam) {+ const { context, modelId, columnId, recordId, scope, attachment } = param;++ const baseModel = await getBaseModelSqlFromModelId({+ context: context,+ modelId: modelId,+ });+ await baseModel.model.getColumns(context);+ const column = baseModel.model.columns.find((col) => col.id === columnId);++ // Check if column exists in model+ if (!column) {+ NcError.get(context).fieldNotFound(columnId);+ }++ // Get the row data+ const rowData = await baseModel+ .dbDriver(baseModel.getTnPath(baseModel.model))+ .where(await _wherePk(baseModel.model.primaryKeys, recordId, true))+ .first();++ if (!rowData) {+ NcError.get(context).recordNotFound(recordId);+ }++ if (!attachment.contentType || !attachment.file || !attachment.filename) {+ NcError.get(context).invalidRequestBody(+ `Field contentType, file and filename is required`,+ );+ }++ const processedAttachments = [];+ const generateThumbnailAttachments = [];++ try {+ const storageAdapter = await NcPluginMgrv2.storageAdapter();+ const mimeType = attachment.contentType.split(';')[0].trim();++ let filename = attachment.filename;+ filename = scope+ ? `${normalizeFilename(path.parse(filename).name)}${path.extname(+ filename,+ )}`+ : `${normalizeFilename(path.parse(filename).name)}_${nanoid(+ 5,+ )}${path.extname(filename)}`;++ const filePath = path.join(+ context.workspace_id,+ context.base_id,+ modelId,+ column.id,+ );+ const destPath = path.join('nc', scope ?? 'uploads', filePath);++ const buffer = Buffer.from(attachment.file, 'base64');++ // Calculate file size from base64 value+ const fileSize = buffer.length;++ const resultAttachmentUrl = await storageAdapter.fileCreateByStream(+ slash(path.join(destPath, filename)),+ new PassThrough().end(buffer),+ );++ const processedAttachment = {+ id: nanoid(), // Generate a new ID for the attachment+ url: resultAttachmentUrl,+ path: path.join('download', filePath, filename),+ title: filename,+ mimetype: mimeType,+ size: fileSize,+ };+ processedAttachments.push(processedAttachment);+ if (thumbnailMimes.some((type) => mimeType.startsWith(type))) {+ generateThumbnailAttachments.push(processedAttachment);+ }+ } catch (error) {+ NcError.unprocessableEntity(+ `Failed to process base64 attachment: ${error}`,+ );+ }++ // Update the cell field using baseModel.dbDriver directly+ const currentAttachments = rowData[column.column_name]+ ? JSON.parse(rowData[column.column_name])+ : [];+ const updatedAttachments = [...currentAttachments, ...processedAttachments];++ await baseModel+ .dbDriver(baseModel.getTnPath(baseModel.model))+ .update({+ [column.column_name]: JSON.stringify(updatedAttachments),+ })+ .where(await _wherePk(baseModel.model.primaryKeys, recordId, true));++ if (generateThumbnailAttachments.length > 0) {+ await this.jobsService.add(JobTypes.ThumbnailGenerator, {+ context: {+ base_id: RootScopes.ROOT,+ workspace_id: RootScopes.ROOT,+ },+ attachments: generateThumbnailAttachments,+ scope,+ });+ }++ await baseModel.updateLastModified({+ rowIds: [recordId],+ cookie: { user: context.user },+ baseModel,+ knex: baseModel.dbDriver,+ model: baseModel.model,+ });+ // TODO: audit log++ return await this.dataV3Service.dataRead(context, {+ modelId,+ query: '',+ req: { context, user: context.user } as any,+ rowId: recordId,+ });+ }+protected async downloadAndStoreAttachment({url,filePath,diff --git a/packages/nocodb/src/types/data-columns/attachment.ts b/packages/nocodb/src/types/data-columns/attachment.tsindex b2214b12be..da28d33b11 100644--- a/packages/nocodb/src/types/data-columns/attachment.ts+++ b/packages/nocodb/src/types/data-columns/attachment.ts@@ -28,3 +28,16 @@ export interface AttachmentUrlUploadParam {url: string;}[];}++export interface AttachmentBase64UploadParam {+ context: NcContext;+ scope?: PublicAttachmentScope;+ modelId: string;+ columnId: string;+ recordId: string;+ attachment: {+ contentType: string;+ file: string; // base64-encoded-file-content+ filename: string;+ };+}diff --git a/packages/nocodb/tests/unit/rest/tests/dataApiV3/attachment.test.ts b/packages/nocodb/tests/unit/rest/tests/dataApiV3/attachment.test.tsindex 4322e94a10..1c84988821 100644--- a/packages/nocodb/tests/unit/rest/tests/dataApiV3/attachment.test.ts+++ b/packages/nocodb/tests/unit/rest/tests/dataApiV3/attachment.test.ts@@ -7,6 +7,7 @@ import {beforeEach as dataApiV3BeforeEach,} from './beforeEach';import { ncAxios } from './ncAxios';+import type { INcAxios } from './ncAxios';const API_VERSION = 'v3';describe('Attachment V3', () => {@@ -18,9 +19,9 @@ describe('Attachment V3', () => {let ncAxiosGet: INcAxios['ncAxiosGet'];let ncAxiosPatch: INcAxios['ncAxiosPatch'];+ const base64Image =+ 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0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p1.body.fields.Attachment[0].id,);});+ it('Upload file and update from base64', async () => {+ const rsp = await ncAxiosPost({+ url: `${urlPrefix}/${table.id}/records`,+ body: [+ {+ fields: {+ Attachment: [],+ },+ },+ ],+ });++ expect(rsp.body.records.length).to.eq(1);+ expect(rsp.body.records[0].fields.Attachment.length).to.eq(0);+ const recordId = rsp.body.records[0].id;+ const columnId = table.columns.find((col) => col.title === 'Attachment').id;++ const rspPatch1 = await ncAxiosPost({+ url: `${urlPrefix}/${table.id}/records/${recordId}/columns/${columnId}/upload`,+ body: {+ contentType: 'image/png',+ file: base64Image,+ filename: 'photo.png',+ },+ });++ expect(rspPatch1.body.fields.Attachment.length).to.eq(1);+ expect(rspPatch1.body.fields.Attachment[0].mimetype).to.eq('image/png');+ const rspPatch2 = await ncAxiosPost({+ url: `${urlPrefix}/${table.id}/records/${recordId}/columns/${columnId}/upload`,+ body: {+ contentType: 'image/png',+ file: base64Image,+ filename: 'photo.png',+ },+ });+ expect(rspPatch2.body.fields.Attachment.length).to.eq(2);+ expect(rspPatch2.body.fields.Attachment[1].mimetype).to.eq('image/png');+ });});