Home > Blockchain >  react native: unable to upload file to server : Network request failed
react native: unable to upload file to server : Network request failed

Time:02-22

I'm trying to upload a file to the north, but the file is not sent to the server and react native throws an error in the console: Network request failed. I tried to test api through Postman. The file is uploading successfully. My options are over. I would be very happy for a hint what I'm doing wrong.

code UploadPage:

// Import React
import React, { useState } from 'react';
// Import core components
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

// Import Document Picker
import DocumentPicker from 'react-native-document-picker';

const UploadPage = ({ navigation }) => {
  const [singleFile, setSingleFile] = useState(null);

  const uploadImage = async () => {
    // Check if any file is selected or not
    if (singleFile != null) {
      // If file selected then create FormData
      const fileToUpload = singleFile;
      const data = new FormData();
      data.append('file_attachment', fileToUpload);
      // Please change file upload URL
      let res = await fetch('http://10.0.2.2:8080/upload.php',
        {
          method: 'post',
          body: data,
          headers: {
            'Content-Type': 'multipart/form-data; ',
          },
        }
      );
      let responseJson = await response.json(); {
        alert('Upload Successful');
        console.log('responseJson '   responseJson);
      }
    } else {
      // If no file selected the show alert
      alert('Please Select File first');
      console.log('Fucking Error: '   error);
    }
  };

  const selectFile = async () => {
    // Opening Document Picker to select one file
    try {
      const res = await DocumentPicker.pick({
        // Provide which type of file you want user to pick
        type: [DocumentPicker.types.allFiles],
        // There can me more options as well
        // DocumentPicker.types.allFiles
        // DocumentPicker.types.images
        // DocumentPicker.types.plainText
        // DocumentPicker.types.audio
        // DocumentPicker.types.pdf
      });
      // Printing the log realted to the file
      console.log('res : '   JSON.stringify(res));
      // Setting the state to show single file attributes
      setSingleFile(res);
    } catch (err) {
      setSingleFile(null);
      // Handling any exception (If any)
      if (DocumentPicker.isCancel(err)) {
        // If user canceled the document selection
        alert('Canceled');
      } else {
        // For Unknown Error
        alert('Unknown Error: '   JSON.stringify(err));
        throw err;
      }
    }
  };
  return (
    <View style={styles.mainBody}>
      <View style={{ alignItems: 'center' }}>
        
      </View>
      {/*Showing the data of selected Single file*/}
      {singleFile != null ? (
        <Text style={styles.textStyle}>
          File Name: {singleFile.name ? singleFile.name : ''}
          {'\n'}
          Type: {singleFile.type ? singleFile.type : ''}
          {'\n'}
        </Text>
      ) : null}
      <TouchableOpacity
        style={styles.buttonStyle}
        activeOpacity={0.5}
        onPress={selectFile}>
        <Text style={styles.buttonTextStyle}>Select File</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.buttonStyle}
        activeOpacity={0.5}
        onPress={uploadImage}>
        <Text style={styles.buttonTextStyle}>Upload File</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  mainBody: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },
  buttonStyle: {
    backgroundColor: '#307ecc',
    borderWidth: 0,
    color: '#FFFFFF',
    borderColor: '#307ecc',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 15,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
  textStyle: {
    backgroundColor: '#fff',
    fontSize: 15,
    marginTop: 16,
    marginLeft: 35,
    marginRight: 35,
    textAlign: 'center',
  },
});

export default UploadPage;

Code PHP API:

<?php
 
    // Type your website name or domain name here.
    $domain_name = "http://localhost:8080/" ;
    
    // Image uploading folder.
    $target_dir = "uploads";
    
    // Generating random image name each time so image name will not be same .
    $target_dir = $target_dir . "/" .rand() . "_" . time() . ".jpeg";
    
    // Receiving image tag sent from application.
    
    // Receiving image sent from Application    
    if(move_uploaded_file($_FILES['filetoupload']['tmp_name'], $target_dir)){
        
        // Adding domain name with image random name.
        $target_dir = $domain_name . $target_dir ;
        
        // Inserting data into MySQL database.
        
        $MESSAGE = "Image Uploaded Successfully." ;
            
        // Printing response message on screen after successfully inserting the image . 
        echo json_encode($MESSAGE);
    }
?>

Console log:

When a file is selected, "res" is displayed in the console. When sending, it shows "Network request failed"

When sending a file via PostMan, it is successfully uploaded to the server.

CodePudding user response:

try changing this line

data.append('data', fileToUpload);

with

data.append("data", {type: 'image/jpg', uri:fileToUpload, name:fileToUpload});
  • Related