0

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?

Mikha Matta
  • 189
  • 3
  • 4
  • 16

1 Answers1

0

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();


Fiston Emmanuel
  • 4,242
  • 1
  • 8
  • 14
  • thanks for your answer. i am using document.picker not image picker. https://github.com/rnmods/react-native-document-picker#documentpickerpickmultipleoptions--documentpickerpicksingleoptions--documentpickerpickoptions what shoud i change in my code to match your answer? – Mikha Matta Feb 02 '22 at 11:15
  • Sorry for mishap, I updated the answer – Fiston Emmanuel Feb 02 '22 at 11:23
  • thanks for updating answer. i did what you said. i put fileToUpload[0].uri like: xhr.open("GET", fileToUpload[0].uri, true); console.log(blob) = {"_data": {"__collector": {}, "blobId": "86D1C8F3-B32E-48EA-AC31-C265571F628D", "name": "D0BED0E3-4567-41DA-9B21-8C409E355A87.JPG", "offset": 0, "size": 1454366, "type": "application/octet-stream"}}. so what i shoud do in php? – Mikha Matta Feb 02 '22 at 11:25
  • this is my axios: axios.post(''+ALL.API_URL+'/sellwithus/upload.php', blob, { headers: { 'Content-Type': 'multipart/form-data; ', } }) .then((response) => { console.log(response); }) – Mikha Matta Feb 02 '22 at 11:25
  • I don't know how your PHP backend handle BLOB data, I tested this solution with cloud object hosting providers like Amazon S3 or Firebase Storage – Fiston Emmanuel Feb 02 '22 at 11:28
  • may you help me figure out how should php code looks like ? i am getting an array of $_POST["_data"] in my php code but i dont know how to continue – Mikha Matta Feb 02 '22 at 11:34
  • {"config": {"adapter": [Function xhrAdapter], "data": "{\"_data\":{\"size\":1454366,\"offset\":0,\"blobId\":\"B2A0E58B-D819-449E-9380-6888D2FE23C5\",\"type\":\"application/octet-stream\",\"name\":\"D0BED0E3-4567-41DA-9B21-8C409E355A87.JPG\",\"__collector\":{}}}", "headers": {"Accept": "application/json, text/plain, */*", "Content-Type": "multipart/form-data; "} – Mikha Matta Feb 02 '22 at 11:35
  • look at this https://stackoverflow.com/questions/36044064/saving-blob-object-as-a-file-on-server – Fiston Emmanuel Feb 02 '22 at 11:44
  • not working :\ any other solution? – Mikha Matta Feb 02 '22 at 22:39