【问题标题】:How to upload an audio clip from react-native to php backend?如何将音频剪辑从 react-native 上传到 php 后端?
【发布时间】:2017-01-11 08:13:17
【问题描述】:

尝试了许多 3rd 方库,例如 axios、fetch、fetch-blob,但均未成功。 此代码包括我的 php 后端。 使用 rn v 0.39

将手机存储中已存在的音频片段上传到服务器

文件路径:AudioUtils.MusicDirectoryPath + '/test.aac' [有路径,可以播放片段]

使用参考:/github.com/g6ling/react-native-uploader

Server response

“无法检索 uri /storage/emulated/0/Music/test.aac 的文件”

权限

<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" />  

反应原生代码

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 代码

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');
    }          
}

【问题讨论】:

  • 当你的代码被执行时究竟会发生什么?
  • echo json_encode('status'=>'文件上传错误');
  • 请检查服务器响应,我如何上传这个

标签: javascript php codeigniter reactjs react-native


【解决方案1】:

修复

使用的库 - react-native-fetch-blob

代码

    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)

  })

【讨论】:

  • 我正在使用上面的代码并从服务器获得响应 201 你能帮我吗
猜你喜欢
  • 2021-07-30
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多