react native 头像上传 react-native-image-crop-picker

之前用的是react-native-image-picker,但是当往服务器端传的时候才发现,因为没有图片裁切,所以图片过大,无法保存,所以只好更换成react-native-image-crop-picker。
react-native-image-crop-picker 不像 react-native-image-picker 直接就有弹出框,然后根据选择跳入到相应的相机或相册中,所以需要我们自定义弹出框,这里使用的是 modal。
react-native-image-crop-picker 的导入及配置这里就不说了,可以参考github上:
https://github.com/ivpusic/react-native-image-crop-picker
1、自定义弹出框(modal)
react native 提供的 Alert 局限性较大,没有办法自定义,所以我这里选择用 Modal 来实现。
简单了解:Modal组件可以用来覆盖包含 react native 根视图的原生视图,在嵌入 react native 的混合应用中可以使用 modal,modal 可以使你应用中 RN 编写的那部分内容覆盖在原生视图上显示。
常见属性:

visible // 是否可见  false/true
animationType  // 动画  none:无/slide:从底部/fade:淡入淡出            
transparent = {true}  // 是否默认半透明
onRequestClose={()=> this.onRequestClose()}  // 弹出框关闭回调

     this.onRequestClose()}
    >
        
            
                请选择
                
                    打开相机
                
                
                    打开相册
                
                
                    取消
                
            
        
    

用 state 中 modalVisible 的状态来管理弹出框的显示与关闭。
style样式:

alertBackground:{
    flex:1,
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'rgba(0, 0, 0, 0.5)’,  // 如果要遮罩要显示成半透明状态,这里一定要设置,reba中的a控制透明度,取值在 0.0 ~ 1.0 范围内。
},

alertBox: {
    width:200,
    height:175,
    backgroundColor:'white',
},

_openCamera: // 调用相机,这里就要用到 react-native-image-crop-picker 了,所以记得 import 它。
// 是一个异步加载,当正确是返回 image ,这里面就是我们需要的图片信息。

ImagePicker.openCamera({
    width:300,
    height:400,
    cropping:true
}).then(image => {
    let source = {uri: image.path};

    this._fetchImage(image);

    this.setState({
        avatarSource: source  // 将图片存于本地
    });
});

_openPicker: // 调用相册

ImagePicker.openPicker({
    width:300,
    height:400,
    cropping: true
}).then(image => {
    let source = {uri: image.path};

    this._fetchImage(image);

    this.setState({
       avatarSource: source
    });
});

将图片文件上传:

_fetchImage(image) {
    let url = “http:。。。。。。。。”; // 接口地址
    let file = {uri: image.path, type: 'multipart/form-data', name:’image.png' } ; // file 中这三个元素缺一不可。 type 必须为 multipart/form-data。

    let formData = new FormData();
    formData.append('file', file); // 这里的 file 要与后台名字对应。

    fetch(url,{
        method:'POST',
        headers:{
            'Content-Type':'multipart/form-data',
        },
        body:formData,
    }).then(function (response) {
        console.log("response",response);
        return response.json();
    })
}

你可能感兴趣的:(react native 头像上传 react-native-image-crop-picker)