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

IT技术 reactjs
2021-05-27 12:10:26

我正在尝试将 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) => { 

我该如何解决这个问题?我试过为头像创建一个状态/props,但这引发了错误。

1个回答

有 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) => {