tasks.task.file.attach
Прикрепить файлы к задаче v 3.0
Описание
Метод относится к REST 3.0. Особенности вызова и формат ответа новой версии API описаны в обзоре REST 3.0.
Метод tasks.task.file.attach добавляет файлы с Диска в задачу. У пользователя должен быть доступ к файлу на чтение или выше.
Параметры
taskId
integer
обязательный
Идентификатор задачи, к которой нужно прикрепить файлы.
Идентификатор задачи можно получить при создании новой задачи или старым методом получения списка задач
fileIds
integer[]
обязательный
Массив идентификаторов файлов Диска.
Получить идентификаторы файлов можно двумя способами.
Использовать один из методов загрузки файла:
- disk.storage.uploadfile
- disk.folder.uploadfile
Использовать один из методов получения списка файлов:
- disk.storage.getchildren
- disk.folder.getchildren
Примеры запроса
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"taskId":8017,"fileIds":[1065,1077]}' \
https://**put_your_bitrix24_address**/rest/api/**put_your_user_id_here**/**put_your_webhook_here**/tasks.task.file.attach
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"taskId":8017,"fileIds":[1065,1077],"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/api/tasks.task.file.attach
// 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 } from '@bitrix24/b24jssdk'
declare const $b24: B24Frame
// Shape of the payload returned in result (match the "response handling" section of the page)
type AttachFileResult = {
result: boolean
}
try {
const response = await $b24.actions.v3.call.make<AttachFileResult>({
method: 'tasks.task.file.attach',
params: {
taskId: 8017,
fileIds: [1065, 1077],
},
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('Files attached successfully:', result.result)
}
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
<!-- 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 attachTaskFiles() {
try {
// Initialize the SDK inside a Bitrix24 frame
const $b24 = await B24Js.initializeB24Frame()
const response = await $b24.actions.v3.call.make({
method: 'tasks.task.file.attach',
params: {
taskId: 8017,
fileIds: [1065, 1077],
},
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('Files attached successfully:', result.result)
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
}
document.addEventListener('DOMContentLoaded', attachTaskFiles)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
try:
bitrix_response = client.tasks.task.file.attach(
task_id=8017,
file_ids=[
1065,
1077,
],
).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}")
try {
$response = $b24Service
->core
->call(
'tasks.task.file.attach',
[
'taskId' => 8017,
'fileIds' => [1065, 1077]
]
);
$result = $response
->getResponseData()
->getResult();
echo 'Success: ' . print_r($result, true);
processData($result);
} catch (Throwable $e) {
error_log($e->getMessage());
echo 'Error attaching file: ' . $e->getMessage();
}
BX24.callMethod(
'tasks.task.file.attach',
{
taskId: 8017,
fileIds: [1065, 1077]
},
function(result){
console.info(result.data());
console.log(result);
}
);
require_once('crest.php');
$result = CRest::call(
'tasks.task.file.attach',
[
'taskId' => 8017,
'fileIds' => [1065, 1077]
]
);
echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "tasks.task.file.attach", b24.Params{
"taskId": 8017,
"fileIds": []int{1065, 1077},
})
if err != nil {
return fmt.Errorf("tasks.task.file.attach: %w", err)
}
var item struct {
Result bool `json:"result"`
}
if err := json.Unmarshal(res.Result, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.Result)
Ответ
HTTP-статус: 200
{
"result": {
"result": true
},
"time": {
"start": 1765357239,
"finish": 1765357239.724951,
"duration": 0.7249510288238525,
"processing": 0,
"date_start": "2025-12-10T12:00:39+03:00",
"date_finish": "2025-12-10T12:00:39+03:00",
"operating_reset_at": 1765357839,
"operating": 0
}
}
Возвращаемые данные
result
boolean
Корневой элемент ответа.
Содержит объект с ключом result и значением true, если файл прикреплен успешно
time
time
Информация о времени выполнения запроса
Обработка ошибок
HTTP-статус: 400
{
"error": {
"code": "BITRIX_REST_V3_EXCEPTION_VALIDATION_REQUESTVALIDATIONEXCEPTION",
"message": "Ошибка при валидации объекта запроса",
"validation": [
{
"message": "Обязательное поле `taskId` не указано",
"field": "taskId"
}
]
}
}
| Код | Описание | Значение |
|---|---|---|
Поле |
Описание ошибки | Как исправить |
taskId fileIds |
Обязательное поле #FIELD# не указано |
Добавьте указанное поле в тело запроса |
FIELD# |
В поле #FIELD# требуется тип данных #TYPE# для такого запроса |
Убедитесь, что передаваемое значение нужного типа |
— |
Недостаточно прав | Нет доступа к указанному файлу или задаче |

