Error while uploading image to server using form data in react-native

88 Views Asked by At

Images are uploading using postman but it is giving error in React Native

import React, { useState } from "react";
import { Button, Image, TextInput, View, Alert } from "react-native";
import axios from "axios";
import \* as ImagePicker from 'react-native-image-picker';

const App = () =\> {
const \[image, setImage\] = useState(null);
const \[description, setDescription\] = useState("");

const handleChooseImage = async () =\> {
const options = {
mediaType: "photo", // Specify media type as 'photo' for images
};

// Launch the image picker
ImagePicker.launchImageLibrary(options, (response) => {
  if (response.didCancel) {
    // User cancelled image selection
    return;
  } else if (response.error) {
    // Handle any errors that occurred during image selection
    console.error(response.error);
    return;
  }

  // Set the selected image URI
  setImage({
    uri: response.uri,
    name: response.fileName,
    type: response.type,
  });
  });

};

const handleUploadImage = async () =\> {
if (!image) {
Alert.alert("Error", "Please select an image to upload.");
return;
}

// Create a FormData object to send the image and description
const formData = new FormData();
formData.append("image", image);
formData.append("des", description);

try {
  const response = await axios.post(
    "http://19x.xxx.x.xx4:7000/upload", 
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );

  if (response.status === 200) {
    // Image uploaded successfully
    Alert.alert("Success", "Image uploaded successfully!");
  } else {
    // Handle server response indicating an error
    Alert.alert("Error", "Something went wrong while uploading the image.");
  }
} catch (error) {
  // Handle network or other errors
  console.error(error);
  Alert.alert("Error", "An error occurred while uploading the image.");
}

};

return (
\<View\>
\<Image source={image} style={{ width: 200, height: 200 }} /\>
 \    <Button title="Choose Image" onPress={handleChooseImage} /\>
 \<TextInput
    placeholder="Enter description"
    value={description}
    onChangeText={setDescription}
  /\>
\<Button title="Upload Image" onPress={handleUploadImage} /\>
 \</View\>
 );
 };

 export default App;

first erroe was ReactImageView: Image source "null" doesn't exist

now it's giving

[AxiosError: Network Error] ERROR [AxiosError: Network Error]

Images are uploading using postman but it is giving error in Application

I want to upload images in mysql server and display it in application

0

There are 0 best solutions below