2017-02-10 5 views
4

내 카메라 롤 또는 API로 이미지를 업로드하는 데 문제가 있습니다. 여기에 내가 현재 사용하고있는 코드가있다. 카메라 롤과 카메라에서 이미지 데이터를 가져올 수 있습니다. 난 그냥 서버에 데이터를 게시하는 문제가 있습니다. 내가 혼란스러워하는 곳을 모른다. 여기React Native image upload

import React, { Component } from 'react'; 
import { 
    Text, 
    View, 
    PixelRatio, 
    TouchableOpacity, 
    Image, 
    Platform, 
    NativeModules, 
    DeviceEventEmitter 
} from 'react-native'; 
import { connect } from 'react-redux'; 
import ImagePicker from 'react-native-image-picker'; 
import { captureProflieAvitar } from '../../actions'; 

var RNUploader = NativeModules.RNUploader; 
class NewCamera extends Component { 
    state = { 
    avatarSource: null, 
    imgBase64: [] 
    } 
    componentDidMount() { 
    // upload progress 
    DeviceEventEmitter.addListener('RNUploaderProgress', (data) => { 
     const bytesWritten = data.totalBytesWritten; 
     const bytesTotal = data.totalBytesExpectedToWrite; 
     const progress = data.progress; 
     console.log(bytesWritten, bytesTotal); 
     console.log("upload progress: " + progress + "%"); 
    }); 
} 

    selectPhotoTapped() { 
    const options = { 
     quality: 0.75, 
     maxWidth: 300, 
     maxHeight: 300, 
     storageOptions: { 
     skipBackup: true 
     } 
    }; 
    ImagePicker.showImagePicker(options, (response) => { 
     console.log('Response = ', response); 

     if (response.didCancel) { 
     console.log('User cancelled photo picker'); 
     } else if (response.error) { 
     console.log('ImagePicker Error: ', response.error); 
     } else if (response.customButton) { 
     console.log('User tapped custom button: ', response.customButton); 
     } else { 
     let source; 
     // You can display the image using either: 
     source = { uri: 'data:image/jpeg;base64,' + response.data, isStatic: true }; 

     const temp = response.data; 

     //Or: 
     if (Platform.OS === 'android') { 
      source = { uri: response.uri, isStatic: true }; 
     } else { 
      source = { uri: response.uri.replace('file://', ''), isStatic: true }; 
     } 

     this.setState({ 
      avatarSource: source, 
      imgBase64: temp, 
     }); 
     } 
    }); 
    } 

doUpload() { 

    const files = { 
      filepath: `data:image/png;base64,${this.state.imgBase64}`, 
     }; 
    const opts = { 
     url: 'https://central.tipflip.co?apior=MYAPIKEY&tfReqID3031&tfUserID=1&tfImage=', 
     files, 
     method: 'POST', 
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 
    }; 

    RNUploader.upload(opts, (err, response) => { 
     if (err) { 
      console.log(err); 
      return; 
     } 
     const status = response.status; 
     const responseString = response.data; 
     const json = JSON.parse(responseString); 
     console.log('upload complete with status ' + status); 
    }); 
} 
    render() { 
    return (
     <View style={styles.container}> 
     <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> 
      <View style={[styles.avatar, styles.avatarContainer, { marginBottom: 20 }]}> 
      { this.state.avatarSource === null ? <Text>Select a Photo</Text> : 
      <Image style={styles.avatar} source={this.state.avatarSource} /> 
      } 
      </View> 
     </TouchableOpacity> 

     <TouchableOpacity 
      style={{ 
      backgroundColor: 'yellow', 
      width: 60, 
      height: 20, 
      marginTop: 20, 
      justifyContent: 'center', 
      alignItems: 'center' }} 
      onPress={this.doUpload.bind(this)} 
     > 
      <Text>Upload</Text> 
     </TouchableOpacity> 

     <TouchableOpacity 
     style={{ 
      backgroundColor: 'yellow', 
      width: 60, 
      height: 20, 
      marginTop: 20, 
      justifyContent: 'center', 
      alignItems: 'center' 
      }} onPress={this.props.cancel} 
     > 
      <Text>Cancel</Text> 
     </TouchableOpacity> 

     </View> 
    ); 
    } 
} 
const styles = { 
    container: { 
    justifyContent: 'center', 
    alignItems: 'center' 
    }, 
    avatarContainer: { 
    borderColor: '#9B9B9B', 
    borderWidth: 1/PixelRatio.get(), 
    justifyContent: 'center', 
    alignItems: 'center' 
    }, 
    avatar: { 
    borderRadius: 75, 
    width: 150, 
    height: 150 
    } 

}; 
export default connect(null, { captureProflieAvitar })(NewCamera); 
+0

를 사용하여 이미지를 업로드하는 것입니다? – martinarroyo

+0

빈 데이터가있는 객체를 얻는 중입니다. 내 문제는 내가 게시물 데이터를 올바르게 형식화하지 않는다고 생각합니다. –

+0

API에 대해 상태 200이 표시되지만 데이터가 나타나지 않습니다. –

답변

1

예는 와이어의 다른 쪽 끝오고있다 무엇 Fetch API

var photo = { 
    uri: user.profilePicture, 
    type: 'image/jpeg', 
    name: 'photo.jpg', 
}; 

var form = new FormData(); 
form.append("ProfilePicture", photo); 

fetch(
    Constants.API_USER + 'me/profilePicture', 
    { 
    body: form, 
    method: "PUT", 
    headers: { 
     'Content-Type': 'multipart/form-data', 
     'Authorization': 'Bearer ' + user.token 
    } 
    } 
).then((response) => response.json()) 
.catch((error) => { 
    alert("ERROR " + error) 
}) 
.then((responseData) => { 
    alert("Succes "+ responseData) 
}).done(); 

크레딧 https://stackoverflow.com/a/36649457/5315786

+0

'이미지/jpeg'가 될 것임을 어떻게 확신합니까? 그렇다면 ReactNative 또는이 질문에서 언급 한 ImagePicker 패키지가 어떻게 그 문제를 해결할 수 있습니까? – Trip