Reputation: 95
Tried many 3rd party librairies like axios,fetch,fetch-blob w/o success. this code includes my php backend. using rn v 0.39
upload an audio clip that already exists in phone storage to server
file path : AudioUtils.MusicDirectoryPath + '/test.aac' [have access to the path , can play the clip ]
using reference: /github.com/g6ling/react-native-uploader
"Could not retrieve file for uri /storage/emulated/0/Music/test.aac"
Permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
React-native code
const form= new FormData();
form.append('userfile', {
uri: AudioUtils.MusicDirectoryPath + '/test.aac',
type: 'audio/aac',
name: 'userfile'
});
let xhr = new XMLHttpRequest()
xhr.open('post', `http://vidyarangam.com/next/upload_file`)
xhr.send(form)
xhr.onerror = function(e) {
console.log('err', e)
}
xhr.onreadystatechange = function() {
if(this.readyState === this.DONE) {
console.log(this.response)
}
}
php code
function upload_file() {
$droidinput = json_decode(file_get_contents('php://input'), true);
$file = $droidinput['userfile']; // i have no idea how to upload it
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
$config['max_size'] = '1024'; //1 MB
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo json_encode('status'=>'File upload error');
} else {
echo json_encode('status'=>'File successfully uploaded');
}
}
Upvotes: 2
Views: 3916
Reputation: 99
FIX
used lib - react-native-fetch-blob
code
import RNFetchBlob from 'react-native-fetch-blob';
let dirs = RNFetchBlob.fs.dirs;
let path_to_a_file = dirs.DownloadDir + '/header_logo.png';
RNFetchBlob.fetch('POST', 'http://192.168.43.236/upload.php', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
{ name : 'header_logo', filename : 'header_logo.png', type:'image/foo', data:RNFetchBlob.wrap(path_to_a_file)},
]).then((resp) => {
console.log(resp.text())
}).catch((err) => {
console.log(err)
})
Upvotes: 2