How to upload images to Cloudflare Images using an Expo App

I am using Axios and React Native Expo. I am getting the image from the user using the expo-image-picker library. I want to get images from my users and upload them to Cloudflare images how can I do that? I have also tried uploading Digital Ocean Spaces but that too gives similar errors. I want a image hosting service that works with my expo app. Cloudinairy is very expensive.

I have tried the official docs but am running into errors, here is the code I used-

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { View, Text, TextInput, Alert, TouchableOpacity, Image } from 'react-native';
import React, { useState, useEffect } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as Icon from 'react-native-feather';
import { themeColors } from '../theme';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import * as ImagePicker from 'expo-image-picker';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
import 'react-native-url-polyfill/auto';
import { ReadableStream } from 'web-streams-polyfill';
globalThis.ReadableStream = ReadableStream;
// Replace these with your actual Cloudflare account details
const CLOUDFLARE_ACCOUNT_ID = '';
const CLOUDFLARE_API_TOKEN = '';
export default function AddItems({ navigation }) {
const [produceName, setProduceName] = useState('');
const [quantity, setQuantity] = useState('');
const [price, setPrice] = useState('');
const [itemImage, setItemImage] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [uploading, setUploading] = useState(false);
useEffect(() => {
const loadPhoneNumber = async () => {
try {
const storedPhoneNumber = await AsyncStorage.getItem('phone');
if (storedPhoneNumber) {
setPhoneNumber(storedPhoneNumber);
} else {
Alert.alert('Error', 'Phone number not found');
}
} catch (error) {
console.error('Error loading phone number from AsyncStorage:', error);
}
};
loadPhoneNumber();
}, []);
const pickImageAsync = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
quality: 1,
});
if (!result.canceled) {
uploadImage(result.assets[0]);
} else {
alert('You did not select any image.');
}
};
const getImageBlob = async (uri) => {
const response = await fetch(uri);
const blob = await response.blob();
return blob;
};
const uploadImage = async (imageAsset) => {
setUploading(true);
const customPath = `${uuidv4()}-${produceName.replace(/s+/g, '-').toLowerCase()}`;
try {
const blob = await getImageBlob(imageAsset.uri);
const formData = new FormData();
formData.append('file', blob, 'image.jpg');
formData.append('id', customPath);
console.log('Uploading to Cloudflare...');
console.log('FormData:', JSON.stringify(formData));
const response = await axios.post(
`https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/images/v1`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`,
},
timeout: 30000, // Increased timeout to 30 seconds
}
);
console.log('Cloudflare response:', response.data);
if (response.data.success) {
const imageUrl = response.data.result.variants[0];
setItemImage(imageUrl);
Alert.alert('Success', 'Image uploaded successfully');
} else {
throw new Error('Upload failed: ' + JSON.stringify(response.data.errors));
}
} catch (error) {
console.error('Error uploading image:', error);
if (error.response) {
console.error('Error data:', error.response.data);
console.error('Error status:', error.response.status);
console.error('Error headers:', error.response.headers);
} else if (error.request) {
console.error('Error request:', error.request);
} else {
console.error('Error message:', error.message);
}
Alert.alert('Error', `Failed to upload image: ${error.message}`);
} finally {
setUploading(false);
}
};
const handleSubmit = async () => {
if (!produceName || !quantity || !price) {
Alert.alert('Error', 'All fields are required');
return;
}
try {
const formData = {
phoneNumber,
itemName: produceName,
quantity,
price,
itemImage,
};
const response = await axios.post(
'myurl/api/supplier/add-item',
formData
);
if (response.status === 200) {
Alert.alert('Success', 'Item added successfully!');
navigation.goBack();
}
} catch (error) {
console.error('Error adding item:', error.response?.data || error.message);
Alert.alert(
'Error',
error.response?.data?.message || 'Failed to add item, please try again'
);
}
};
return (
//frontend code
);
}
</code>
<code>import { View, Text, TextInput, Alert, TouchableOpacity, Image } from 'react-native'; import React, { useState, useEffect } from 'react'; import { SafeAreaView } from 'react-native-safe-area-context'; import * as Icon from 'react-native-feather'; import { themeColors } from '../theme'; import AsyncStorage from '@react-native-async-storage/async-storage'; import axios from 'axios'; import * as ImagePicker from 'expo-image-picker'; import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; import 'react-native-url-polyfill/auto'; import { ReadableStream } from 'web-streams-polyfill'; globalThis.ReadableStream = ReadableStream; // Replace these with your actual Cloudflare account details const CLOUDFLARE_ACCOUNT_ID = ''; const CLOUDFLARE_API_TOKEN = ''; export default function AddItems({ navigation }) { const [produceName, setProduceName] = useState(''); const [quantity, setQuantity] = useState(''); const [price, setPrice] = useState(''); const [itemImage, setItemImage] = useState(''); const [phoneNumber, setPhoneNumber] = useState(''); const [uploading, setUploading] = useState(false); useEffect(() => { const loadPhoneNumber = async () => { try { const storedPhoneNumber = await AsyncStorage.getItem('phone'); if (storedPhoneNumber) { setPhoneNumber(storedPhoneNumber); } else { Alert.alert('Error', 'Phone number not found'); } } catch (error) { console.error('Error loading phone number from AsyncStorage:', error); } }; loadPhoneNumber(); }, []); const pickImageAsync = async () => { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, quality: 1, }); if (!result.canceled) { uploadImage(result.assets[0]); } else { alert('You did not select any image.'); } }; const getImageBlob = async (uri) => { const response = await fetch(uri); const blob = await response.blob(); return blob; }; const uploadImage = async (imageAsset) => { setUploading(true); const customPath = `${uuidv4()}-${produceName.replace(/s+/g, '-').toLowerCase()}`; try { const blob = await getImageBlob(imageAsset.uri); const formData = new FormData(); formData.append('file', blob, 'image.jpg'); formData.append('id', customPath); console.log('Uploading to Cloudflare...'); console.log('FormData:', JSON.stringify(formData)); const response = await axios.post( `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/images/v1`, formData, { headers: { 'Content-Type': 'multipart/form-data', 'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`, }, timeout: 30000, // Increased timeout to 30 seconds } ); console.log('Cloudflare response:', response.data); if (response.data.success) { const imageUrl = response.data.result.variants[0]; setItemImage(imageUrl); Alert.alert('Success', 'Image uploaded successfully'); } else { throw new Error('Upload failed: ' + JSON.stringify(response.data.errors)); } } catch (error) { console.error('Error uploading image:', error); if (error.response) { console.error('Error data:', error.response.data); console.error('Error status:', error.response.status); console.error('Error headers:', error.response.headers); } else if (error.request) { console.error('Error request:', error.request); } else { console.error('Error message:', error.message); } Alert.alert('Error', `Failed to upload image: ${error.message}`); } finally { setUploading(false); } }; const handleSubmit = async () => { if (!produceName || !quantity || !price) { Alert.alert('Error', 'All fields are required'); return; } try { const formData = { phoneNumber, itemName: produceName, quantity, price, itemImage, }; const response = await axios.post( 'myurl/api/supplier/add-item', formData ); if (response.status === 200) { Alert.alert('Success', 'Item added successfully!'); navigation.goBack(); } } catch (error) { console.error('Error adding item:', error.response?.data || error.message); Alert.alert( 'Error', error.response?.data?.message || 'Failed to add item, please try again' ); } }; return ( //frontend code ); } </code>
import { View, Text, TextInput, Alert, TouchableOpacity, Image } from 'react-native';
import React, { useState, useEffect } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as Icon from 'react-native-feather';
import { themeColors } from '../theme';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import * as ImagePicker from 'expo-image-picker';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
import 'react-native-url-polyfill/auto';
import { ReadableStream } from 'web-streams-polyfill';
globalThis.ReadableStream = ReadableStream;

// Replace these with your actual Cloudflare account details
const CLOUDFLARE_ACCOUNT_ID = '';
const CLOUDFLARE_API_TOKEN = '';

export default function AddItems({ navigation }) {
  const [produceName, setProduceName] = useState('');
  const [quantity, setQuantity] = useState('');
  const [price, setPrice] = useState('');
  const [itemImage, setItemImage] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    const loadPhoneNumber = async () => {
      try {
        const storedPhoneNumber = await AsyncStorage.getItem('phone');
        if (storedPhoneNumber) {
          setPhoneNumber(storedPhoneNumber);
        } else {
          Alert.alert('Error', 'Phone number not found');
        }
      } catch (error) {
        console.error('Error loading phone number from AsyncStorage:', error);
      }
    };

    loadPhoneNumber();
  }, []);

  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      uploadImage(result.assets[0]);
    } else {
      alert('You did not select any image.');
    }
  };

  const getImageBlob = async (uri) => {
    const response = await fetch(uri);
    const blob = await response.blob();
    return blob;
  };
  
  const uploadImage = async (imageAsset) => {
    setUploading(true);
    const customPath = `${uuidv4()}-${produceName.replace(/s+/g, '-').toLowerCase()}`;
  
    try {
      const blob = await getImageBlob(imageAsset.uri);
  
      const formData = new FormData();
      formData.append('file', blob, 'image.jpg');
      formData.append('id', customPath);
  
      console.log('Uploading to Cloudflare...');
      console.log('FormData:', JSON.stringify(formData));
      
      const response = await axios.post(
        `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/images/v1`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${CLOUDFLARE_API_TOKEN}`,
          },
          timeout: 30000, // Increased timeout to 30 seconds
        }
      );
  
      console.log('Cloudflare response:', response.data);
  
      if (response.data.success) {
        const imageUrl = response.data.result.variants[0];
        setItemImage(imageUrl);
        Alert.alert('Success', 'Image uploaded successfully');
      } else {
        throw new Error('Upload failed: ' + JSON.stringify(response.data.errors));
      }
    } catch (error) {
      console.error('Error uploading image:', error);
      if (error.response) {
        console.error('Error data:', error.response.data);
        console.error('Error status:', error.response.status);
        console.error('Error headers:', error.response.headers);
      } else if (error.request) {
        console.error('Error request:', error.request);
      } else {
        console.error('Error message:', error.message);
      }
      Alert.alert('Error', `Failed to upload image: ${error.message}`);
    } finally {
      setUploading(false);
    }
  };

  const handleSubmit = async () => {
    if (!produceName || !quantity || !price) {
      Alert.alert('Error', 'All fields are required');
      return;
    }

    try {
      const formData = {
        phoneNumber,
        itemName: produceName,
        quantity,
        price,
        itemImage,
      };

      const response = await axios.post(
        'myurl/api/supplier/add-item',
        formData
      );

      if (response.status === 200) {
        Alert.alert('Success', 'Item added successfully!');
        navigation.goBack();
      }
    } catch (error) {
      console.error('Error adding item:', error.response?.data || error.message);
      Alert.alert(
        'Error',
        error.response?.data?.message || 'Failed to add item, please try again'
      );
    }
  };

  return (
    //frontend code
  );
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật