tasks.task.files.attach
Прикрепить файлы к задаче
Описание
Метод tasks.task.files.attach добавляет файл с Диска в задачу. У пользователя должен быть доступ к файлу на чтение или выше.
Параметры
taskId
integer
обязательный
Идентификатор задачи, к которой нужно прикрепить файл.
Идентификатор задачи можно получить при создании новой задачи или методом получения списка задач
fileId
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,"fileId":1065}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/tasks.task.files.attach
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"taskId":8017,"fileId":1065,"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/tasks.task.files.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 = {
attachmentId: number
}
try {
const response = await $b24.actions.v2.call.make<AttachFileResult>({
method: 'tasks.task.files.attach',
params: {
taskId: 8017,
fileId: 1065,
},
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('Attachment ID:', result.attachmentId)
}
} 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 attachFile() {
try {
// Initialize the SDK inside a Bitrix24 frame
const $b24 = await B24Js.initializeB24Frame()
const response = await $b24.actions.v2.call.make({
method: 'tasks.task.files.attach',
params: {
taskId: 8017,
fileId: 1065,
},
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('Attachment ID:', result.attachmentId)
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
}
document.addEventListener('DOMContentLoaded', attachFile)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
try:
bitrix_response = client.tasks.task.files.attach(
task_id=8017,
file_id=1065,
).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.files.attach',
[
'taskId' => 8017,
'fileId' => 1065
]
);
$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.files.attach',
{
taskId: 8017,
fileId: 1065
},
function(result){
console.info(result.data());
console.log(result);
}
);
require_once('crest.php');
$result = CRest::call(
'tasks.task.files.attach',
[
'taskId' => 8017,
'fileId' => 1065
]
);
echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "tasks.task.files.attach", b24.Params{
"taskId": 8017,
"fileId": 1065,
})
if err != nil {
return fmt.Errorf("tasks.task.files.attach: %w", err)
}
var item struct {
AttachmentID b24.ID `json:"attachmentId"`
}
if err := json.Unmarshal(res.Result, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.AttachmentID)
Ответ
HTTP-статус: 200
{
"result": {
"attachmentId": 1079
},
"time": {
"start": 1758806783,
"finish": 1758806783.609955,
"duration": 0.6099550724029541,
"processing": 0,
"date_start": "2025-09-25T16:26:23+03:00",
"date_finish": "2025-09-25T16:26:23+03:00",
"operating_reset_at": 1758807383,
"operating": 0.4156019687652588
}
}
Возвращаемые данные
result
object
Корневой элемент ответа. Содержит объект с описанием прикрепленного файла
attachmentId
integer
Идентификатор прикрепления файла к задаче.
Получить данные о файле по идентификатору прикрепления можно методом disk.attachedObject.get
time
time
Информация о времени выполнения запроса
Обработка ошибок
HTTP-статус: 400
{
"error": "100",
"error_description": "Could not find value for parameter {fileId} (internal error)"
}
| Код | Описание | Значение |
|---|---|---|
100 |
CTaskItem All parameters in the constructor must have real class type (internal error) | Не указан обязательный параметр taskId |
0 |
wrong task id (internal error) | В параметре taskId указано значение неверного типа |
100 |
Could not find value for parameter \{fileId\} (internal error) | Не указан обязательный параметр fileId |
100 |
Invalid value {value} to match with parameter \{fileId\}. Should be value of type int. (internal error) | В параметре fileId указано значение неверного типа |
ERROR_CORE |
Недостаточно прав.\\u003Cbr\\u003E | Нет доступа к указанному файлу |
0 |
Access denied (internal error) | Недостаточно прав на изменение задачи |

