简体   繁体   中英

React native upload image or file via php

i am using document picker to upload an image via php.

this is my js code:


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('name', 'imgup');
      data.append('attachement_file', fileToUpload);
      
      axios.post(''+ALL.API_URL+'/sellwithus/upload.php', data, {
        headers: {
          'Content-Type': 'multipart/form-data; ',
        }
      })
      .then((response) => {
        console.log(response);
      })

    } else {
      // If no file selected the show alert
      alert('Please Select File first');
    }
  };


the select code:


  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.images],
        // 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;
      }
    }
  };

this is the res result:

console.log(JSON.stringify(res));

res:[{"size":1454366,"fileCopyUri":null,"name":"D0BED0E3-4567-41DA-9B21-8C409E355A87.JPG","uri":"file:///Users/saeedmatar/Library/Developer/CoreSimulator/Devices/098A7371-530E-4667-AAAF-80EAE97F9A9E/data/Containers/Data/Application/06A2878B-D812-4B3C-BEF0-2E40DBFE9A27/tmp/org.reactjs.native.example.JelApp-Inbox/D0BED0E3-4567-41DA-9B21-8C409E355A87.JPG"}]

this is my php code:

$_POST = json_decode(file_get_contents("php://input"),true);

$imageData=$_POST["_parts"][1][1][0];

file_put_contents('uploads/image.JPG', $imageData["uri"]);

the image that uploaded is 0 mb and not appearing.

how can i use uri to upload the image?

File uri returned by react-native-document-picker is a reference in the device app local cache and can't be used to upload data.

Fetch and upload document BLOB data.


 const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", [DOCUMENT_PATH_URI_HERE], true);
    xhr.send(null);
  });

// code to submit blob data


// We're done with the blob, close and release it
  blob.close();


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM