មគ្គុទេសក៍ពេញលេញសម្រាប់ការបញ្ចូលឯកសារទៅកាន់ Blue ដោយប្រើការប្រែប្រួល GraphQL ឬ REST API


ការពិពណ៌នា

មគ្គុទេសក៍នេះបង្ហាញពីរបៀបបញ្ចូលឯកសារទៅកាន់ Blue ដោយប្រើវិធីសាស្ត្រចំនួនពីរ៖

  1. ការបញ្ចូល GraphQL ដោយផ្ទាល់ (ផ្តល់អនុសាសន៍) - ការបញ្ចូលមួយជំហានដែលមានកំណត់ទំហំឯកសារ 256MB
  2. ការបញ្ចូល REST API - ដំណើរការបីជំហានដែលគាំទ្រទំហំឯកសារធំជាង 4.8GB

នេះគឺជាការប្រៀបធៀបរវាងវិធីសាស្ត្រទាំងពីរ៖

លក្ខណៈ ការបញ្ចូល GraphQL ការបញ្ចូល REST API
Complexity Simple (one request) Complex (three steps)
File Size Limit 256MB per file 4.8GB per file
Batch Upload Up to 10 files Single file only
Implementation Direct mutation Multi-step process
Best For Most use cases Large files only

ការបញ្ចូលឯកសារ GraphQL

វិធីសាស្ត្របញ្ចូល GraphQL ផ្តល់នូវវិធីសាស្ត្រងាយស្រួល និងផ្ទាល់ខ្លួនសម្រាប់បញ្ចូលឯកសារជាមួយសំណើមួយ។

uploadFile

បញ្ចូលឯកសារមួយទៅកាន់ប្រព័ន្ធផ្ទុកឯកសារ ហើយបង្កើតយោងឯកសារនៅក្នុងមូលដ្ឋានទិន្នន័យ។

Input:

  • file: Upload! - ឯកសារដែលត្រូវបញ្ចូល (ប្រើ multipart/form-data)
  • projectId: String! - ID ឬ slug នៃគម្រោងដែលឯកសារនឹងត្រូវបានផ្ទុក
  • companyId: String! - ID ឬ slug នៃក្រុមហ៊ុនដែលឯកសារនឹងត្រូវបានផ្ទុក

Returns: File! - វត្ថុឯកសារដែលបានបង្កើត

Example:

mutation UploadFile($input: UploadFileInput!) {
  uploadFile(input: $input) {
    id
    uid
    name
    size
    type
    extension
    shared
    createdAt
    project {
      id
      name
    }
    folder {
      id
      title
    }
  }
}

uploadFiles

បញ្ចូលឯកសារជាច្រើនទៅកាន់ប្រព័ន្ធផ្ទុកឯកសារ ហើយបង្កើតយោងឯកសារនៅក្នុងមូលដ្ឋានទិន្នន័យ។

Input:

  • files: [Upload!]! - អារ៉ាយនៃឯកសារដែលត្រូវបញ្ចូល (អតិបរមា 10)
  • projectId: String! - ID ឬ slug នៃគម្រោងដែលឯកសារនឹងត្រូវបានផ្ទុក
  • companyId: String! - ID ឬ slug នៃក្រុមហ៊ុនដែលឯកសារនឹងត្រូវបានផ្ទុក

Returns: [File!]! - អារ៉ាយនៃវត្ថុឯកសារដែលបានបង្កើត

Example:

mutation UploadFiles($input: UploadFilesInput!) {
  uploadFiles(input: $input) {
    id
    uid
    name
    size
    type
    extension
    shared
    createdAt
  }
}

ការអនុវត្តន៍ Client

Apollo Client (JavaScript)

ការបញ្ចូលឯកសារមួយ:

import { gql } from '@apollo/client';

const UPLOAD_FILE = gql`
  mutation UploadFile($input: UploadFileInput!) {
    uploadFile(input: $input) {
      id
      uid
      name
      size
      type
      extension
      shared
      createdAt
    }
  }
`;

// Using file input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

const { data } = await uploadFile({
  variables: {
    input: {
      file: file,
      projectId: "project_123", // or "my-project-slug"
      companyId: "company_456"  // or "my-company-slug"
    }
  }
});

Multiple Files Upload:

const UPLOAD_FILES = gql`
  mutation UploadFiles($input: UploadFilesInput!) {
    uploadFiles(input: $input) {
      id
      uid
      name
      size
      type
      extension
      shared
      createdAt
    }
  }
`;

// Using multiple file inputs
const fileInputs = document.querySelectorAll('input[type="file"]');
const files = Array.from(fileInputs).map(input => input.files[0]).filter(Boolean);

const { data } = await uploadFiles({
  variables: {
    input: {
      files: files,
      projectId: "project_123", // or "my-project-slug"
      companyId: "company_456"  // or "my-company-slug"
    }
  }
});
@@CB##36e5a432-d888-4488-b300-ffddbc5aa024##CB@@html
<!-- HTML -->
<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload File</button>
@@CB##a86b8d78-6124-4dab-a3c9-9cd1e2a6bb91##CB@@javascript
async function uploadFile() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];

  if (!file) {
    alert('Please select a file');
    return;
  }

  // Create GraphQL mutation
  const query = `
    mutation UploadFile($input: UploadFileInput!) {
      uploadFile(input: $input) {
        id
        name
        size
        type
        extension
        createdAt
      }
    }
  `;

  // Prepare form data
  const formData = new FormData();
  formData.append('operations', JSON.stringify({
    query: query,
    variables: {
      input: {
        file: null, // Will be replaced by file
        projectId: "your_project_id", // or "your-project-slug"
        companyId: "your_company_id"  // or "your-company-slug"
      }
    }
  }));

  formData.append('map', JSON.stringify({
    "0": ["variables.input.file"]
  }));

  formData.append('0', file);

  try {
    const response = await fetch('/graphql', {
      method: 'POST',
      body: formData,
      headers: {
        // Don't set Content-Type - let browser set it with boundary
        'Authorization': 'Bearer your_auth_token'
      }
    });

    const result = await response.json();

    if (result.errors) {
      console.error('Upload failed:', result.errors);
      alert('Upload failed: ' + result.errors[0].message);
    } else {
      console.log('Upload successful:', result.data.uploadFile);
      alert('File uploaded successfully!');
    }
  } catch (error) {
    console.error('Network error:', error);
    alert('Network error during upload');
  }
}

Multiple Files Upload:

<!-- HTML -->
<input type="file" id="filesInput" multiple />
<button onclick="uploadFiles()">Upload Files</button>
@@CB##dfa9a6a0-0e87-469e-9e04-f5c5a9fe3a99##CB@@javascript
async function uploadFiles() {
  const filesInput = document.getElementById('filesInput');
  const files = Array.from(filesInput.files);

  if (files.length === 0) {
    alert('Please select files');
    return;
  }

  if (files.length > 10) {
    alert('Maximum 10 files allowed');
    return;
  }

  const query = `
    mutation UploadFiles($input: UploadFilesInput!) {
      uploadFiles(input: $input) {
        id
        name
        size
        type
        extension
        createdAt
      }
    }
  `;

  const formData = new FormData();

  // Create file placeholders for variables
  const fileVariables = files.map((_, index) => null);

  formData.append('operations', JSON.stringify({
    query: query,
    variables: {
      input: {
        files: fileVariables,
        projectId: "your_project_id", // or "your-project-slug"
        companyId: "your_company_id"  // or "your-company-slug"
      }
    }
  }));

  // Create map for file replacements
  const map = {};
  files.forEach((_, index) => {
    map[index.toString()] = [`variables.input.files.${index}`];
  });
  formData.append('map', JSON.stringify(map));

  // Append actual files
  files.forEach((file, index) => {
    formData.append(index.toString(), file);
  });

  try {
    const response = await fetch('/graphql', {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': 'Bearer your_auth_token'
      }
    });

    const result = await response.json();

    if (result.errors) {
      console.error('Upload failed:', result.errors);
      alert('Upload failed: ' + result.errors[0].message);
    } else {
      console.log('Upload successful:', result.data.uploadFiles);
      alert(`${result.data.uploadFiles.length} ឯកសារបញ្ចូលដោយជោគជ័យ!`);
    }
  } catch (error) {
    console.error('Network error:', error);
    alert('Network error during upload');
  }
}
@@CB##a1cc92b8-079e-4415-b0c1-15cf532074d3##CB@@bash
# Single file upload with cURL
curl -X POST \
  -H "Authorization: Bearer your_auth_token" \
  -F 'operations={"query":"mutation UploadFile($input: UploadFileInput!) { uploadFile(input: $input) { id name size type extension createdAt } }","variables":{"input":{"file":null,"projectId":"your_project_id","companyId":"your_company_id"}}}' \
  -F 'map={"0":["variables.input.file"]}' \
  -F '0=@/path/to/your/file.jpg' \
  https://your-api.com/graphql

REST API Upload

Use this method for files larger than 256MB (up to 4.8GB). This approach uses a three-step process: request upload credentials, upload to storage, then register the file in the database.

Prerequisites:

  • Python 3.x installed
  • requests library installed: pip install requests
  • A valid X-Bloo-Token-ID and X-Bloo-Token-Secret for Blue API authentication
  • The file to upload (e.g., test.jpg) in the same directory as the script

This method covers two scenarios:

  1. Uploading to the "File Tab"
  2. Uploading to the "Todo File Custom Field"

Configuration

Define these constants at the top of your script:

@@CB##4692cd5b-71c7-430c-8f14-b0964361422a##CB@@

This is diagram that shows the flow of the upload process:

Upload Process

Uploading to File Tab

::code-group

import requests
import json
import os

# Configuration
FILENAME = "test.jpg"
TOKEN_ID = "YOUR_TOKEN_ID"
TOKEN_SECRET = "YOUR_TOKEN_SECRET"
COMPANY_ID = "YOUR_COMPANY_ID_OR_SLUG"
PROJECT_ID = "YOUR_PROJECT_ID_OR_SLUG"
BASE_URL = "https://api.blue.cc"

# Headers for Blue API
HEADERS = {
    "X-Bloo-Token-ID": TOKEN_ID,
    "X-Bloo-Token-Secret": TOKEN_SECRET,
    "X-Bloo-Company-ID": COMPANY_ID,
    "X-Bloo-Project-ID": PROJECT_ID,
}

# Step 1: Get upload credentials
def get_upload_credentials():
    url = f"{BASE_URL}/uploads?filename={FILENAME}"
    response = requests.get(url, headers=HEADERS)
    if response.status_code != 200:
        raise Exception(f"Failed to fetch upload credentials: {response.status_code} - {response.text}")
    return response.json()

# Step 2: Upload file to S3
def upload_to_s3(credentials):
    s3_url = credentials["url"]
    fields = credentials["fields"]
    
    files = {
        "acl": (None, fields["acl"]),
        "Content-Disposition": (None, fields["Content-Disposition"]),
        "Key": (None, fields["Key"]),
        "X-Key": (None, fields["X-Key"]),
        "Content-Type": (None, fields["Content-Type"]),
        "bucket": (None, fields["bucket"]),
        "X-Amz-Algorithm": (None, fields["X-Amz-Algorithm"]),
        "X-Amz-Credential": (None, fields["X-Amz-Credential"]),
        "X-Amz-Date": (None, fields["X-Amz-Date"]),
        "Policy": (None, fields["Policy"]),
        "X-Amz-Signature": (None, fields["X-Amz-Signature"]),
        "file": (FILENAME, open(FILENAME, "rb"), fields["Content-Type"])
    }
    
    response = requests.post(s3_url, files=files)
    if response.status_code != 204:
        raise Exception(f"S3 upload failed: {response.status_code} - {response.text}")
    print("S3 upload successful")

# Step 3: Register file with Blue
def register_file(file_uid):
    graphql_url = f"{BASE_URL}/graphql"
    headers = HEADERS.copy()
    headers["Content-Type"] = "application/json"
    
    query = """
    mutation CreateFile($uid: String!, $name: String!, $type: String!, $extension: String!, $size: Float!, $projectId: String!, $companyId: String!) {
        createFile(input: {uid: $uid, name: $name, type: $type, size: $size, extension: $extension, projectId: $projectId, companyId: $companyId}) {
            id
            uid
            name
            __typename
        }
    }
    """
    
    variables = {
        "uid": file_uid,
        "name": FILENAME,
        "type": "image/jpeg",
        "extension": "jpg",
        "size": float(os.path.getsize(FILENAME)),  # Dynamic file size
        "projectId": PROJECT_ID,
        "companyId": COMPANY_ID
    }
    
    payload = {
        "operationName": "CreateFile",
        "query": query,
        "variables": variables
    }
    
    response = requests.post(graphql_url, headers=headers, json=payload)
    if response.status_code != 200:
        raise Exception(f"GraphQL registration failed: {response.status_code} - {response.text}")
    print("File registration successful:", response.json())

# Main execution
def main():
    try:
        if not os.path.exists(FILENAME):
            raise Exception(f"File '{FILENAME}' not found")
        
        # Step 1: Fetch credentials
        credentials = get_upload_credentials()
        print("Upload credentials fetched:", credentials)
        
        # Step 2: Upload to S3
        upload_to_s3(credentials)
        
        # Step 3: Register file
        file_uid = credentials["fields"]["Key"].split("/")[0]
        register_file(file_uid)
        
        print("Upload completed successfully!")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

::

Steps Explained

Step 1: Request Upload Credentials

  • Send a GET request to https://api.blue.cc/uploads?filename=test.jpg@@CODE##3edb4f59-424f-4fae-8501-b144684c52ef##CODE@@files@@CODE##4b9f44de-18c2-4e61-b332-0d085ac88830##CODE@@requests.post@@CODE##3f7d8cf7-4d67-422e-bacb-cb7285fb9fbe##CODE@@https://api.blue.cc/graphql
  • Dynamically calculates file size with os.path.getsize

Sample Response:
@@CB##74663f64-2d25-4a99-9998-f1f9c682922f##CB@@

Uploading to Custom Field

::code-group

@@CB##2ec83d9f-bc2f-4525-a37c-5f58980e0ea7##CB@@
::

Steps 1-3 are the same as the File Tab process (fetch credentials, upload to S3, and register file metadata).

For step 4, you need to associate the file with a todo custom field.

  • Sends a GraphQL mutation to link the file to a todo custom field
  • Uses `todoId@@CODE##fa509914-5f09-419f-a1c8-0910a912ad7c##CODE@@customFieldId@@CODE##5ee524e0-f19e-4d64-9546-e36f264054ab##CODE@@``json
    {
    "data": {
    "createTodoCustomFieldFile": true
    }
    }

ជំនួយក្រុមហ៊ុន AI

ការឆ្លើយតបត្រូវបានបង្កើតឡើងដោយប្រើ AI ហើយអាចមានកំហុស។

ខ្ញុំអាចជួយអ្នកបានយ៉ាងដូចម្តេច?

សូមសួរអ្វីក៏បានអំពី Blue ឬឯកសារនេះ។

ចូលដើម្បីផ្ញើ • Shift+Enter សម្រាប់បន្ទាត់ថ្មី • ⌘I ដើម្បីបើក