简体   繁体   English

如何使用React Native从文件系统中检索文件,以转换为base64和以JSON形式进行http发布?

[英]How can I retrieve a file from the file system using React Native, for conversion to base64 and http posting as JSON?

I am using the react native template from this article . 我现在用的是从反应本土模板这篇文章 The code is all available on Github here . 该代码是所有可用在Github 这里

You can use the app to record audio and save to the file system. 您可以使用该应用程序录制音频并保存到文件系统。 I figured out how to retrieve the file URIs, but I'm finding it impossible to get the actual contents of the file itself. 我想出了如何获取文件URI的方法,但是我发现无法获取文件本身的实际内容。 All I want to do is retrieve the actual file contents as a binary or ascii or hex string or whatever (it's a .m4a file), so I can convert it to base64 encoding and then post it as JSON to my server. 我要做的就是检索二进制或ascii或十六进制字符串等形式的实际文件内容(这是一个.m4a文件),因此我可以将其转换为base64编码,然后将其作为JSON发布到我的服务器。 Here's what my code looks like: 这是我的代码:

/src/screens/RecordAudioScreen/RecordAudioScreenContainer.js /src/screens/RecordAudioScreen/RecordAudioScreenContainer.js

onEndRecording: props => async () => {
  try {
    // here is the URI
    console.log("HERE IS THE URI!!");
    const audio_data = "URI: " + props.recording._uri;

    // Help needed here
    // retrieve file contents from the Android/iOS file system
    // Encode as base64
    audio_data = ... // ???????

    // this works already, posts to the server
    fetch("https://myserver.com/accept_file",
    {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify({user_id: 1, audio_data: audio_data})
    })
    .then(function(res){ console.log(res) })
    .catch(function(res){ console.log(res) });
    console.log("FINISHED POST REQUEST!!!")

    await props.recording.stopAndUnloadAsync();
    await props.setAudioMode({ allowsRecordingIOS: false });

  } catch (error) {
    console.log(error); // eslint-disable-line
  }

  if (props.recording) {
    const fileUrl = props.recording.getURI();
    props.recording.setOnRecordingStatusUpdate(null);
    props.setState({ recording: null, fileUrl });
  }
},

I've already tried a bunch of stuff with no success. 我已经尝试了很多东西,但都没有成功。 Ideally I just get the file contents from the File system, convert to base64 and post it off all in this method just in javascript, but this is seemingly very difficult for what should be a pretty standard thing to do in an app based framework. 理想情况下,我只是从File系统中获取文件内容,将其转换为base64并将其通过javascript中的所有方法发布出去,但这对于在基于应用程序的框架中应该是相当标准的事情似乎非常困难。

Here's some stack overflow questions on React Native Fetch Blob which I couldn't make work Fetch Blob 1 Fetch Blob 2 这是关于React Native Fetch Blob的一些堆栈溢出问题,我无法正常工作Fetch Blob 1 Fetch Blob 2

I've tried using React Native Fs , but I can't get it to load properly, I got super bogged down in stuff I didn't understand after trying to eject the app. 我已经尝试过使用React Native Fs了 ,但是我无法使其正确加载,在尝试退出该应用程序后,我陷入了我不了解的东西的超级困惑。 I'd prefer a plain React Native solution if possible. 如果可能的话,我更喜欢一个简单的React Native解决方案。

I've also tried some code using FormData but couldn't get that to work either. 我还尝试了一些使用FormData的代码,但也无法正常工作。

Maybe the answer is kind of like this question about retrieving images from firebase ? 也许答案有点像关于从Firebase检索图像的问题 I don't know, this is my first attempt at doing anything in React. 我不知道,这是我在React中做任何事情的第一次尝试。

It might also have something to do with the "file://" prefix in the URI that gets generated because there's a lot of questions discussing removing that (only for Android, or only for iOS I'm not too clear). 它也可能与生成的URI中的“ file://”前缀有关,因为在讨论删除该前缀时有很多问题(仅针对Android,或者对于iOS,我不太清楚)。

Converting to base64 will be done with something like this , but I need the actual file contents first: 转换为Base64将做这样的事情 ,但我首先需要实际的文件内容:

Very appreciative of any help. 非常感谢您的帮助。

Some time ago I wrote a simple example of a record voice app. 前段时间,我写了一个简单的录音语音应用程序示例。

To get the files I used this method: 要获取文件,我使用了这种方法:

  import RNFS from 'react-native-fs';

  (...)

  getFiles() {
    RNFS.readDir(AudioUtils.DocumentDirectoryPath)
    .then((result) => {
       this.setState({recordedFiles: result});
       return Promise.all([RNFS.stat(result[0].path), result[0].path]);
    })
    .catch((err) => {
      console.log(err.message, err.code);
    });
  }

It worked just fine. 工作正常。

Here's the full example https://github.com/soutot/react-native-voice-record-app 这是完整的示例https://github.com/soutot/react-native-voice-record-app

Let me know if it helped. 让我知道是否有帮助。 Otherwise we can try a different approach 否则我们可以尝试其他方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将base64编码的音频转换为JSON? - How can i convert base64 encoded audio to JSON? 错误:无法创建文档:文件不是 PDF 格式或损坏,同时使用 react-native-pdf 将 base64 字符串转换为 pdf - Error: cannot create document: File not in PDF format or corrupted, while converting base64 string to pdf using react-native-pdf 如何使用JSON在服务器的响应中传递图像? Base64编码? - How can I pass images in a server's response using JSON? Base64? 我可以从Base64数据创建一个TriggerIO文件实例以传递给forge.request.ajax吗? - Can I create a TriggerIO File instance from Base64 data to pass to forge.request.ajax? 如何在Android中使用文件路径上传文件?如何将文件路径转换为Base64,然后将其转换为JSON数组? - How to upload a file using file path in android?How to convert file path to Base64 and then convert it to JSON array? Phonegap - 如何从base64字符串生成图像文件? - Phonegap - How to generate image file from base64 string? 如何从文件的 URI 中获取 base64? - How to get base64 from file's URI? 使用 React-Native 中的其他数据从以 base64 存储的 JSON 渲染图像 - Render image from JSON stored as base64 with other data in React-Native 我如何在 kotlin android 中将 pdf 文件编码为 base64 字符串 - How can i encode a pdf file to base64 string in kotlin android 如何在Android中将文件转换为base64? - How to convert file to base64 in Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM