• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Uploading Files to Cloudflare R2 from the Frontend (No Axios Needed!)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Are you building a file upload feature for your web app?
Want to keep things fast and efficient without using any backend for the actual upload?
Let me show you how to upload files directly to Cloudflare R2 using a pre-signed URL and plain fetch — no axios, no SDKs, no stress.


Step 1: Generate a Signed Upload URL on the Server
To avoid exposing your R2 credentials on the frontend, you should generate a signed PUT URL on the backend.

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

to read article about generating signed url.

Here’s an example response from your backend API:


{
"signedUrl": "

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

..."
}

Step 2: Upload from the Frontend Using Fetch
Here’s a minimal example using an HTML file input and plain JavaScript:

✅ HTML:


<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>

✅ JavaScript:


async function uploadFile() {
const input = document.getElementById('fileInput');
const file = input.files[0];
if (!file) return alert("Please select a file!");

// 1. Get a signed upload URL from your backend
const res = await fetch(`/api/r2-signed-url?filename=${encodeURIComponent(file.name)}`);
const { signedUrl } = await res.json();

// 2. Upload the file directly to R2
const uploadRes = await fetch(signedUrl, {
method: 'PUT',
body: file,
});

if (uploadRes.ok) {
alert("✅ Upload successful!");
} else {
alert("❌ Upload failed.");
}
}

Why This Works

  • No extra libraries (no axios)
  • Faster uploads because the file goes straight from browser → Cloudflare
  • Secure: your app’s R2 credentials stay on the server
  • Scalable: you don’t stress your backend with file payloads

Don't Forget CORS!
Make sure your R2 bucket has CORS enabled for PUT requests.
Example:


<CORSRule>
<AllowedMethod>PUT</AllowedMethod>
<AllowedOrigin>*</AllowedOrigin> <!-- or restrict to your domain -->
<AllowedHeader>*</AllowedHeader>
</CORSRule>

? Author: Nurul Islam Rimon
? Fullstack Developer | Expertsquad


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу