# crm.documentgenerator.document.upload

URL: https://chugunov.pro/api-bitrix24/crm/document-generator/documents/crm-document-generator-document-upload/
Проверено на Битрикс24 REST API, обновлено 11.09.2026 (ревизия источника fb39d6c).
Источник: официальная документация Битрикс24 (bitrix-tools/b24-rest-docs, лицензия MIT, © Bitrix). Справочник независимый, официальной документацией не является.

Загрузить документ
Scope: `crm`
Кто может выполнять метод: пользователь с правом "изменения" документов генератора документов

## Описание

Метод `crm.documentgenerator.document.upload` загружает готовый документ и прикрепляет его к CRM-объекту.

## Параметры

- `fields` `object` — необязательный. Объект с параметрами загрузки документа [(подробнее)](#fields)

### Параметр fields

- `entityTypeId` `integer` — необязательный. Идентификатор типа CRM-объекта.
  Типичные значения:
  - `1` — лид
  - `2` — сделка
  - `3` — контакт
  - `4` — компания
  - `7` — коммерческое предложение
  Для смарт-процессов передается их `entityTypeId`, например `177`
- `entityId` `integer` — необязательный. Идентификатор CRM-объекта, к которому прикрепляется документ
- `fileContent` `string` — необязательный. Содержимое DOCX-файла в формате base64.
  Подробнее: [Как загружать файлы](https://apidocs.bitrix24.ru/api-reference/files/how-to-upload-files.html)
- `region` `string` — необязательный. Код региона шаблона, например `ru`
- `title` `string` — необязательный. Название документа
- `number` `string` — необязательный. Номер документа
- `pdfContent` `string` — необязательный. Содержимое PDF-файла в формате base64.
  Подробнее: [Как загружать файлы](https://apidocs.bitrix24.ru/api-reference/files/how-to-upload-files.html)
- `imageContent` `string` — необязательный. Содержимое изображения в формате base64.
  Подробнее: [Как загружать файлы](https://apidocs.bitrix24.ru/api-reference/files/how-to-upload-files.html)

## Ответ

HTTP-статус: 200

```json
{
    "result": {
        "document": {
            "changeStampsEnabled": false,
            "changeStampsDisabledReason": "В шаблоне нет печатей и подписей",
            "changeQrCodeEnabled": false,
            "qrCodeEnabled": false,
            "changeQrCodeDisabledReason": "В шаблоне нет QR-кода",
            "products": {
                "currencyId": "UAH",
                "totalSum": "0.00",
                "totalRows": 0
            },
            "downloadUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.download&SITE_ID=s1&id=63",
            "publicUrl": null,
            "title": "Демонстрационная реализация товара",
            "number": "2026-001",
            "id": "63",
            "createTime": "2026-03-20T17:08:24+03:00",
            "createdBy": "577",
            "updateTime": "2026-03-20T17:08:24+03:00",
            "updatedBy": null,
            "stampsEnabled": false,
            "isTransformationError": false,
            "values": {
                "productsTableVariant": "",
                "_creationMethod": "rest"
            },
            "templateId": "55",
            "pullTag": "TRANSFORMDOCUMENT63",
            "emailDiskFile": 5619,
            "entityId": "101",
            "entityTypeId": "2",
            "downloadUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.download.json?auth=***&token=***"
        }
    },
    "time": {
        "start": 1774015704,
        "finish": 1774015705.08562,
        "duration": 1.0856199264526367,
        "processing": 1,
        "date_start": "2026-03-20T17:08:24+03:00",
        "date_finish": "2026-03-20T17:08:25+03:00",
        "operating_reset_at": 1774016304,
        "operating": 1.0284008979797363
    }
}
```

### Возвращаемые данные

- `result` `object`. Корневой объект ответа. Содержит структуру [`result`](#result)
- `time` `time`. Информация о времени выполнения запроса

## Ошибки

HTTP-статус: 400

```json
{
    "error": "100",
    "error_description": "Invalid value {} to match with parameter {fields}. Should be value of type array."
}
```

- `100` — Could not find value for parameter {fields}. Не передан обязательный параметр `fields`
- `100` — Invalid value {} to match with parameter {fields}. Should be value of type array.. Параметр `fields` передан не в формате объекта
- `0` — Empty required fields: entityTypeId, fileContent, region, entityId. Не переданы обязательные поля в `fields`
- `0` — Empty required fields: fileContent. Не передано обязательное поле `fields.fileContent`
- `0` — Wrong "entityTypeId" field value. Передан некорректный `fields.entityTypeId`
- `0` — No provider for entityTypeId. Для `fields.entityTypeId` не найден подходящий CRM-провайдер
- `0` — Wrong "entityId" field value. Передан некорректный `fields.entityId`
- `0` — Missing file content. Не передан или не прочитан `fields.fileContent`
- `0` — Could not save file. Не удалось сохранить загруженный файл
- `0` — Module crm is not installed. Модуль `crm` недоступен на этапе DG-обработки
- `0` — Wrong provider .... Некорректно определен провайдер документа
- `0` — Application not found. Не удалось определить текущее REST-приложение
- `0` — Error generating file for template. Не удалось создать служебный файл для скрытого шаблона
- `0` — Error getting template. Не удалось получить или создать скрытый шаблон для загрузки
- — — You do not have permissions to view documents. Недостаточно прав на просмотр документов
- — — Module documentgenerator is not installed. Модуль `documentgenerator` недоступен

## Примеры запроса

### cURL (Webhook)

```bash
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"entityTypeId":2,"entityId":101,"fileContent":"**base64_docx_content**","region":"ru","title":"Демонстрационная реализация товара","number":"2026-001","pdfContent":"**base64_pdf_content**","imageContent":"**base64_image_content**"}}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/crm.documentgenerator.document.upload
```

### cURL (OAuth)

```bash
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"entityTypeId":2,"entityId":101,"fileContent":"**base64_docx_content**","region":"ru","title":"Демонстрационная реализация товара","number":"2026-001","pdfContent":"**base64_pdf_content**","imageContent":"**base64_image_content**"},"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/crm.documentgenerator.document.upload
```

### JS (TS)

```ts
// This snippet is an ES module: top-level await requires type="module" or a bundler.
// $b24 is an already-initialized SDK instance (see the SDK "Get started" guide).
import { Text } from '@bitrix24/b24jssdk'
import type { B24Frame, ISODate } from '@bitrix24/b24jssdk'

declare const $b24: B24Frame

// Shape of the payload returned in result (match the "response handling" section of the page)
type DocumentUploadResult = {
  document: {
    id: string
    title: string
    number: string
    createTime: ISODate
    updateTime: ISODate
    createdBy: string
    updatedBy: string | null
    changeStampsEnabled: boolean
    changeStampsDisabledReason: string
    changeQrCodeEnabled: boolean
    qrCodeEnabled: boolean
    changeQrCodeDisabledReason: string
    products: {
      currencyId: string
      totalSum: string
      totalRows: number
    }
    stampsEnabled: boolean
    isTransformationError: boolean
    downloadUrl: string
    downloadUrlMachine: string
    publicUrl: string | null
    templateId: string
    pullTag: string
    emailDiskFile: number
    entityTypeId: string
    entityId: string
    values: Record<string, unknown> | null
  }
}

try {
  const response = await $b24.actions.v2.call.make<DocumentUploadResult>({
    method: 'crm.documentgenerator.document.upload',
    params: {
      fields: {
        entityTypeId: 2,
        entityId: 101,
        fileContent: '**base64_docx_content**',
        region: 'ru',
        title: 'Demo Sales Document',
        number: '2026-001',
        pdfContent: '**base64_pdf_content**',
        imageContent: '**base64_image_content**',
      },
    },
    requestId: Text.getUuidRfc4122()
  })

  // The payload is available only on a successful response
  if (!response.isSuccess) {
    console.error(response.getErrorMessages().join('; '))
  } else {
    const result = response.getData()!.result
    console.info(result.document.id, result.document.title, result.document.downloadUrl)
  }
} catch (error) {
  // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
  console.error(error)
}
```

### JS (UMD)

```html
<!-- Load the SDK (UMD build); it is exposed as the global B24Js -->
<script src="https://unpkg.com/@bitrix24/b24jssdk@1/dist/umd/index.min.js"></script>
<script>
  async function uploadDocument() {
    try {
      // Initialize the SDK inside a Bitrix24 frame
      const $b24 = await B24Js.initializeB24Frame()

      const response = await $b24.actions.v2.call.make({
        method: 'crm.documentgenerator.document.upload',
        params: {
          fields: {
            entityTypeId: 2,
            entityId: 101,
            fileContent: '**base64_docx_content**',
            region: 'ru',
            title: 'Demo Sales Document',
            number: '2026-001',
            pdfContent: '**base64_pdf_content**',
            imageContent: '**base64_image_content**',
          },
        },
        requestId: B24Js.Text.getUuidRfc4122()
      })

      // The payload is available only on a successful response
      if (!response.isSuccess) {
        console.error(response.getErrorMessages().join('; '))
        return
      }

      const result = response.getData().result
      console.info(result.document.id, result.document.title, result.document.downloadUrl)
    } catch (error) {
      // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
      console.error(error)
    }
  }

  document.addEventListener('DOMContentLoaded', uploadDocument)
</script>
```

### Python

```python
from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.documentgenerator.document.upload(
        fields={
            "entityTypeId": 2,
            "entityId": 101,
            "fileContent": "**base64_docx_content**",
            "region": "ru",
            "title": "Демонстрационная реализация товара",
            "number": "2026-001",
            "pdfContent": "**base64_pdf_content**",
            "imageContent": "**base64_image_content**",
        },
    ).response
    result = bitrix_response.result
    print(result)
except BitrixAPIError as error:
    print(
        "Ошибка Bitrix API",
        f"error: {error.error}",
        f"error_description: {error.error_description}",
        sep="\n",
    )
except BitrixSDKException as error:
    print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
    print(f"Непредвиденная ошибка: {error}")
```

### PHP

```php
try {
    $response = $b24Service
        ->core
        ->call(
            'crm.documentgenerator.document.upload',
            [
                'fields' => [
                    'entityTypeId' => 2,
                    'entityId' => 101,
                    'fileContent' => '**base64_docx_content**',
                    'region' => 'ru',
                    'title' => 'Демонстрационная реализация товара',
                    'number' => '2026-001',
                    'pdfContent' => '**base64_pdf_content**',
                    'imageContent' => '**base64_image_content**',
                ],
            ]
        );

    $result = $response
        ->getResponseData()
        ->getResult();

    echo '<pre>';
    print_r($result);
    echo '</pre>';

} catch (Throwable $e) {
    error_log($e->getMessage());
    echo 'Error uploading document: ' . $e->getMessage();
}
```

### BX24.js

```js
BX24.callMethod(
    'crm.documentgenerator.document.upload',
    {
        fields: {
            entityTypeId: 2,
            entityId: 101,
            fileContent: '**base64_docx_content**',
            region: 'ru',
            title: 'Демонстрационная реализация товара',
            number: '2026-001',
            pdfContent: '**base64_pdf_content**',
            imageContent: '**base64_image_content**',
        },
    },
    (result) => {
        result.error()
            ? console.error(result.error())
            : console.info(result.data())
        ;
    },
);
```

### PHP CRest

```php
require_once('crest.php');

$result = CRest::call(
    'crm.documentgenerator.document.upload',
    [
        'fields' => [
            'entityTypeId' => 2,
            'entityId' => 101,
            'fileContent' => '**base64_docx_content**',
            'region' => 'ru',
            'title' => 'Демонстрационная реализация товара',
            'number' => '2026-001',
            'pdfContent' => '**base64_pdf_content**',
            'imageContent' => '**base64_image_content**',
        ],
    ]
);

echo '<PRE>';
print_r($result);
echo '</PRE>';
```

### Go

```go
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "crm.documentgenerator.document.upload", b24.Params{
	"fields": b24.Params{
		"entityTypeId": 2,
		"entityId":     101,
		"fileContent":  "**base64_docx_content**",
		"region":       "ru",
		"title":        "Демонстрационная реализация товара",
		"number":       "2026-001",
		"pdfContent":   "**base64_pdf_content**",
		"imageContent": "**base64_image_content**",
	},
})
if err != nil {
	return fmt.Errorf("crm.documentgenerator.document.upload: %w", err)
}

// Метод заворачивает ответ в объект с ключом "document".
raw, ok := b24.Unwrap(res.Result, "document")
if !ok {
	return fmt.Errorf("в ответе нет ключа document")
}

var item struct {
	ChangeStampsEnabled        bool   `json:"changeStampsEnabled"`
	ChangeStampsDisabledReason string `json:"changeStampsDisabledReason"`
	ChangeQrCodeEnabled        bool   `json:"changeQrCodeEnabled"`
	QrCodeEnabled              bool   `json:"qrCodeEnabled"`
	ChangeQrCodeDisabledReason string `json:"changeQrCodeDisabledReason"`
	DownloadUrl                string `json:"downloadUrl"`
}
if err := json.Unmarshal(raw, &item); err != nil {
	return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.ChangeStampsEnabled, item.ChangeStampsDisabledReason)
```

Оригинал в официальной документации: https://apidocs.bitrix24.ru/api-reference/crm/document-generator/documents/crm-document-generator-document-upload.html
