Upload File

Upload a file to a storage zone based on the URL path. If the directory tree does not exist, it will be created automatically.

curl --request PUT \
     --url https://REGION.bunnycdn.com/STORAGE_ZONE_NAME/FILENAME.EXTENSION \ # Replace 'REGION', 'STORAGE_ZONE_NAME' & 'FILENAME.EXTENSION'
     --header 'AccessKey: YOUR_BUNNY_STORAGE_API_KEY' \
     --header 'Content-Type: application/octet-stream' \
     --header 'accept: application/json'  \
     --data-binary @filename.extension
import requests

REGION = 'YOUR_REGION'  # If German region, set this to an empty string: ''
STORAGE_ZONE_NAME = 'YOUR_STORAGE_ZONE_NAME'
FILENAME_EXTENSION = 'YOUR_FILE_NAME'
ACCESS_KEY = 'YOUR_BUNNY_STORAGE_API_KEY'
FILE_PATH = f'/path/to/your/file/on/local/system/{FILENAME_EXTENSION}'

base_url = "storage.bunnycdn.com"
if REGION:
    base_url = f"{REGION}.{base_url}"

url = f"https://{base_url}/{STORAGE_ZONE_NAME}/{FILENAME_EXTENSION}"

headers = {
    "AccessKey": ACCESS_KEY,
    "Content-Type": "application/octet-stream",
    "accept": "application/json"
}

with open(FILE_PATH, 'rb') as file_data:
    response = requests.put(url, headers=headers, data=file_data)

print(response.status_code, response.text)

const https = require('https');
const fs = require('fs');

const REGION = 'YOUR_REGION'; // If German region, set this to an empty string: ''
const BASE_HOSTNAME = 'storage.bunnycdn.com';
const HOSTNAME = REGION ? `${REGION}.${BASE_HOSTNAME}` : BASE_HOSTNAME;
const STORAGE_ZONE_NAME = 'YOUR_STORAGE_ZONE_NAME';
const FILENAME_TO_UPLOAD = 'filenameyouwishtouse.txt';
const FILE_PATH = '/path/to/your/file/upload.txt';
const ACCESS_KEY = 'YOUR_BUNNY_STORAGE_API_KEY';

const uploadFile = async () => {
  const readStream = fs.createReadStream(FILE_PATH);

  const options = {
    method: 'PUT',
    host: HOSTNAME,
    path: `/${STORAGE_ZONE_NAME}/${FILENAME_TO_UPLOAD}`,
    headers: {
      AccessKey: ACCESS_KEY,
      'Content-Type': 'application/octet-stream',
    },
  };

  const req = https.request(options, (res) => {
    res.on('data', (chunk) => {
      console.log(chunk.toString('utf8'));
    });
  });

  req.on('error', (error) => {
    console.error(error);
  });

  readStream.pipe(req);
};

const main = async () => {
  await uploadFile();
};

main();

<?php

$REGION = 'YOUR_REGION';  // If German region, set this to an empty string: ''
$BASE_HOSTNAME = 'storage.bunnycdn.com';
$HOSTNAME = (!empty($REGION)) ? "{$REGION}.{$BASE_HOSTNAME}" : $BASE_HOSTNAME;
$STORAGE_ZONE_NAME = 'YOUR_STORAGE_ZONE_NAME';
$FILENAME_TO_UPLOAD = 'YOUR_FILE_NAME';
$ACCESS_KEY = 'YOUR_BUNNY_STORAGE_API_KEY';
$FILE_PATH = '/path/to/your/file/on/local/system/YOUR_FILE_NAME';  // Full path to your local file

$url = "https://{$HOSTNAME}/{$STORAGE_ZONE_NAME}/{$FILENAME_TO_UPLOAD}";

$ch = curl_init();

$options = array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_PUT => true,
  CURLOPT_INFILE => fopen($FILE_PATH, 'r'),
  CURLOPT_INFILESIZE => filesize($FILE_PATH),
  CURLOPT_HTTPHEADER => array(
    "AccessKey: {$ACCESS_KEY}",
    'Content-Type: application/octet-stream'
  )
);

curl_setopt_array($ch, $options);

$response = curl_exec($ch);

if (!$response) {
  die("Error: " . curl_error($ch));
} else {
  print_r($response);
}

curl_close($ch);

?>

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await UploadFileAsync();
        }

        private static async Task UploadFileAsync()
        {
            const string FILE_PATH = @"/path/to/your/file/upload.txt";  // Full path to your local file
            const string REGION = "YOUR_REGION";  // If German region, set this to an empty string: ""
            const string BASE_HOSTNAME = "storage.bunnycdn.com";
            string HOSTNAME = string.IsNullOrEmpty(REGION) ? BASE_HOSTNAME : $"{REGION}.{BASE_HOSTNAME}";
            const string STORAGE_ZONE_NAME = "YOUR_STORAGE_ZONE_NAME";
            const string FILENAME_TO_UPLOAD = "YOUR_FILE_NAME";
            const string ACCESS_KEY = "YOUR_BUNNY_STORAGE_API_KEY";
            const string CONTENT_TYPE = "application/octet-stream";

            string url = $"https://{HOSTNAME}/{STORAGE_ZONE_NAME}/{FILENAME_TO_UPLOAD}";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            request.ContentType = CONTENT_TYPE;
            request.Headers.Add("AccessKey", ACCESS_KEY);

            using (Stream fileStream = File.OpenRead(FILE_PATH))
            using (Stream requestStream = await request.GetRequestStreamAsync())
            {
                await fileStream.CopyToAsync(requestStream);
            }

            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string responseString = await reader.ReadToEndAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        String storageZoneRegion = ""; // Change to the desired region (leave empty if not applicable)
        String storageZone = "STORAGE_ZONE";
        String fileName = "FILE_NAME";
        String apiKey = "API_KEY";
        String fileLocation = "path/to/file/file.txt";

        try {
            String urlStr;
            if (storageZoneRegion.isEmpty()) {
                urlStr = "https://storage.bunnycdn.com/" + storageZone + "/" + fileName;
            } else {
                urlStr = "https://" + storageZoneRegion + ".storage.bunnycdn.com/" + storageZone + "/" + fileName;
            }

            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("AccessKey", apiKey);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setDoOutput(true);

            File file = new File(fileLocation);
            long fileSize = file.length();

            try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            int responseCode = connection.getResponseCode();
            String responseMsg = connection.getResponseMessage();
            System.out.println("Response: " + responseCode + " " + responseMsg);

            // Handle the response as needed
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Considerations

  • The file content should be sent as the body of the request without any type of encoding. Only raw binary is supported.
  • The storage endpoint hostname is based on the primary region of the storage zone. These are listed below.
  • Checksum hashes if used, must be in SHA256 HEX, and in uppercase.
  • HTTP Request Method: PUT

API Base Endpoint

RegionEndpoint
Falkenstein, DEstorage.bunnycdn.com
London, UKuk.storage.bunnycdn.com
New York, USny.storage.bunnycdn.com
Los Angeles, USla.storage.bunnycdn.com
Singapore, SGsg.storage.bunnycdn.com
Stockholm, SEse.storage.bunnycdn.com
São Paulo, BRbr.storage.bunnycdn.com
Johannesburg, SAjh.storage.bunnycdn.com

Path Parameters

ParamsDescription
storageZoneName (string) requiredThe name of your storage zone where you are connecting to.
path (string) requiredThe directory path to where your file will be stored. If this is the root of your storage zone, you can ignore this parameter.
fileName (string) requiredThe name that the file will be uploaded as.

In summary, a correctly formatted upload URL should resemble: https://{region}.bunnycdn.com/{storageZoneName}/{path}/{fileName}

Request Headers

HeaderDescriptionExample
accesskeyYour bunny.net storage zone API key. For more information regarding accesskey header, see the authentication section.'AccessKey: KEY_GOES_HERE'
content-typeContent type of the file uploaded.'Content-Type: application/octet-stream'

Response Codes

HTTP Status CodeDescription
HTTP 201The file was uploaded successfully.
HTTP 400The file was uploaded unsuccessfully.
HTTP 401Invalid AccessKey, region hostname, or file passed in a non raw binary format.