如何将base64字符串传递给访存API主体有效负载?

时间:2018-08-11 06:40:52

标签: reactjs

我正在尝试将base64字符串传递给API,以便可以存储它。我正在使用图书馆:https://github.com/malsapp/react-native-photo-upload

<PhotoUpload
     onPhotoSelect={avatar => {
       if (avatar) {
    console.log('Image base64 string: ', avatar)
       }
 }}  >
<Image style={{width: 90, height: 90, marginLeft: 10, marginTop: 10, resize: 'cover'}} source = {{uri: 'https://api.helloworld.com/assets/member.png'}}></Image>

使用此代码,我如何将头像传递给有效负载?我想存储base64字符串,以便可以将其存储在代码位于以下的API中:

signup = () => {          
fetch('https://helloworld.app.com/api/signup.json', {
    method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json' },
body: JSON.stringify({
    "name": this.state.name,
    "password": this.state.password,
    "email": this.state.email,
    "avatar": this.state.avatar,
  })
})
.then((response) => response.json())
.then ((res) => { 

我该如何处理?我曾尝试为头像创建状态/道具,但这引发了错误。

1 个答案:

答案 0 :(得分:0)

有一个javascript函数window.btoa(),它将数据编码为Base64字符串:

signup = () => {          
    fetch('https://helloworld.app.com/api/signup.json', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
       'Content-Type': 'application/json' },
      body: JSON.stringify({
        "name": this.state.name,
        "password": this.state.password,
        "email": this.state.email,
        "avatar": window.btoa(this.state.avatar),
  })
})
.then((response) => response.json())
.then ((res) => {