react-native - 如何通过Axios从Expo-av上传录音文件?

标签 react-native axios expo

我正在尝试通过 Axios 发布请求将使用 expo-av 记录的文件上传到我的服务器。请原谅我,我是一名 Python 后端开发人员,所以我对 JS 或 Axios 不是很熟悉。我尝试了各种解决方案,但无法解决任何问题。

我用于录音的代码是这样的,大部分直接来自 Expo 文档(录音元素)并且工作正常(音频文件由模拟器创建,例如 iOS 模拟器的 .caf 文件)

import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [recording, setRecording] = React.useState();

  async function startRecording() {
    try {
      console.log('Requesting permissions..');
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      }); 
      console.log('Starting recording..');
      const { recording } = await Audio.Recording.createAsync(
         Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
      );
      setRecording(recording);
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

  async function stopRecording() {
    console.log('Stopping recording..');
    setRecording(undefined);
    await recording.stopAndUnloadAsync();
    const uri = recording.getURI(); 
    console.log('Recording stopped and stored at', uri);

  //My code for the upload
    const formData = new FormData();
    formData.append("attribute_x", "123");
    formData.append("attribute_y", "456");
    let soundFile = //NOT SURE WHAT THE ACTUAL SOUND FILE IS. The uri is just a string
    formData.append("recording", {uri: uri, name: 'soundfile.caf', type: 'audio/x-caf'});
    const response = await axios.post(my_url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'X-CSRFToken': 'csrftoken',
            }
        })
  ... deal with the response...
  }



  return (
    <View style={styles.container}>
      <Button
        title={recording ? 'Stop Recording' : 'Start Recording'}
        onPress={recording ? stopRecording : startRecording}
      />
    </View>
  );
}

我需要发送的请求体应该是:

{
  "attribute_x": 333,
  "attribute_y": 291,
  "recording": THE SOUND FILE
}

它是 iOS 的 .caf 和 A​​ndroid 的 .mp4(默认值),但我可以自己弄清楚如何处理它。现在上传/发布请求真的让我抓狂。

提前致谢。

最佳答案

我无法让它与 react-native 一起工作,主要原因是 multipart/form-data header 设置不正确,并且 formdata.getHeaders() 未在 react-native 中定义。

尝试了此处测试的所有内容,但没有成功:https://github.com/axios/axios/issues/318

解决方案:使用https://github.com/sindresorhus/ky

const uri = recording.getURI();
const filetype = uri.split(".").pop();
const filename = uri.split("/").pop();
const fd = new FormData();
fd.append("audio-record", {
  uri,
  type: `audio/${filetype}`,
  name: filename,
});
await ky.post("audio/upload", {
  body: fd,
});

headers 会像 fetch api 一样自动设置,并且会提供边界部分!

关于react-native - 如何通过Axios从Expo-av上传录音文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70975373/

相关文章:

azure - 如何在 Node JS Azure 中使用 Expo 部署 React Native Web 应用程序 - 应用服务

android - 如何在Expo App中添加多个url方案而不弹出?

javascript - 使用 Map 函数编写 React 组件时,对象作为 React Child 无效

react-native - 如何在 React Native 中使用 Jest

node.js - NodeJS中axios和supertest的区别

axios - 使用 axios POST 请求传递 header

react-native - 如何使用 async/await 通过使用函数从 AsyncStorage 中检索值以响应 native

javascript - react + Axios : Uncaught (in promise) TypeError: Cannot read property 'map' of undefined

react-native - 模拟 i18n-js 中的 I18n 类,以便在 React Native 中使用 Expo 进行 Jest 测试

javascript - 带有 socket.io websocket 的 Expo 无法连接