Перейти к основному контенту

Отправка формы с вложением файла

✅ Цель сценария:

  • Получить конфигурацию формы из OneEntry CMS
  • Пользователь заполняет форму (например, ответ, отзыв).
  • Прикрепляет файл (изображение, резюме, документ).
  • Данные и файл хранятся вместе в FormData
  • Отправить собранные данные в OneEntry API.

✅ Что вам нужно:

  • Действительный PROJECT_URL и APP_TOKEN для аутентификации с OneEntry API.
  • Форма в OneEntry с полем типа "Файл" (type file)
  • Маркер формы (например, resume_form)

📌 Важно:

  • Мы не обрабатываем ошибки в этих примерах.
  • Вы можете обрабатывать ошибки, используя try-catch или в структуре, подобной "await Promise.catch((error) => error)"

Сценарий

1. Импортируйте oneEntry и определите URL и токен

Пример:

import { defineOneEntry } from 'oneentry';

const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';

2. Создание API-клиента с помощью функции defineOneEntry()

Пример:

const { Forms, FormData } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});

Пример:

const fileForm = await Forms.getFormByMarker('file');
Результат:
{
"id": 8,
"attributeSetId": 11,
"type": "data",
"localizeInfos": {
"title": "Файл",
"titleForSite": "",
"successMessage": "Успешная обработка данных",
"unsuccessMessage": "Неуспешная обработка данных",
"urlAddress": "",
"database": "0",
"script": "0"
},
"version": 0,
"position": 1,
"identifier": "file",
"processingType": "script",
"templateId": null,
"attributes": [
{
"type": "file",
"marker": "file",
"isLogin": null,
"isSignUp": null,
"position": 1,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"localizeInfos": {
"title": "Файл"
},
"additionalFields": [],
"isNotificationEmail": null,
"isNotificationPhoneSMS": null,
"isNotificationPhonePush": null
},
{
"type": "image",
"marker": "image",
"isLogin": null,
"isSignUp": null,
"position": 2,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"localizeInfos": {
"title": "Изображение"
},
"additionalFields": [],
"isNotificationEmail": null,
"isNotificationPhoneSMS": null,
"isNotificationPhonePush": null
},
{
"type": "groupOfImages",
"marker": "images_group",
"isLogin": null,
"isSignUp": null,
"position": 3,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"localizeInfos": {
"title": "Группа изображений"
},
"additionalFields": [],
"isNotificationEmail": null,
"isNotificationPhoneSMS": null,
"isNotificationPhonePush": null
}
]
}

3. Загрузка файла с помощью формы input=file

Отправить

Данные:

// JS
let selectedFiles = null;

// handleFileChange
const handleFileChange = (e: any) => {
selectedFiles = e.target.files;
};

// handleSubmit
const handleSubmit = async (e, file) => {
e.preventDefault();

// 4. Подготовка данных формы
const body = {
formIdentifier: 'file',
formData: [
{
marker: 'file',
type: 'file',
value: file,
fileQuery: {
type: 'page',
entity: 'editor',
id: 4965,
},
},
],
};

// 5. Отправка формы с помощью FormData.postFormsData()
const postFormResp = await FormData.postFormsData(body);
};

Пример:

// HTML
<form
onSubmit={(e) => handleSubmit(e, selectedFiles)}
className="flex flex-col gap-3 p-10 border rounded-3xl"
>
<input
type="file"
onChange={handleFileChange}
className="bg-white text-slate-800 p-3 rounded-2xl"
/>
<button
type="submit"
className="bg-white text-slate-800 p-3 rounded-2xl"
>
Отправить
</button>
</form>
Результат:
{
"formData": {
"formIdentifier": "file",
"time": "2025-05-12T22:28:57.531Z",
"formData": [
{
"marker": "file",
"type": "file",
"value": [
{
"filename": "files/project/page/4965/editor/process-svgrepo-com-1747088937134.svg",
"downloadLink": "https://test-data.oneentry.cloud/cloud-static/files/project/page/4965/editor/process-svgrepo-com-1747088937134.svg",
"size": 67066
}
]
}
],
"id": 76
},
"actionMessage": "Успешная обработка данных"
}

Финальный пример

// 1. Импортируйте oneEntry и определите PROJECT_URL и APP_TOKEN
import { defineOneEntry } from 'oneentry';

const PROJECT_URL = 'your-project-url';
const APP_TOKEN = 'your-app-token';

// 2. Создание API-клиента
const { Forms, FormData } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});

const fileForm = await Forms.getFormByMarker('file');

// 3. Загрузка файла с помощью формы input=file
// JS
const selectedFiles = [];
const handleFileChange = (e) => {
selectedFiles = e.target.files;
};

// handleSubmit
const handleSubmit = async (e, file) => {
e.preventDefault();

// 4. Подготовка данных формы
const body = {
formIdentifier: 'file',
formData: [
{
marker: 'file',
type: 'file',
value: file,
fileQuery: {
type: 'page',
entity: 'editor',
id: 4965,
},
},
],
};

// 5. Отправка формы с помощью FormData.postFormsData()
const postFormResp = await FormData.postFormsData(body);
};

// HTML
<form
onSubmit={(e) => handleSubmit(e, selectedFiles)}
className="flex flex-col gap-3 p-10 border rounded-3xl"
>
<input
type="file"
onChange={handleFileChange}
className="bg-white text-slate-800 p-3 rounded-2xl"
/>
<button
type="submit"
className="bg-white text-slate-800 p-3 rounded-2xl"
>
Отправить
</button>
</form>