美文网首页RNreact native
React-Native 使用react-native-imag

React-Native 使用react-native-imag

作者: 煎包小混沌 | 来源:发表于2017-08-07 18:26 被阅读3474次

    1:先学习react-native-image-crop-picke的使用方法

    导入 react-native-image-crop-picke
    npm i react-native-image-crop-picker --save
    react-native link react-native-image-crop-picker
    
    引用 react-native-image-crop-picke
    import ImagePicker from 'react-native-image-crop-picker';
    
    调用 react-native-image-crop-picke的方法
    //从相册中选择单张图片
    //cropping是否切割
    ImagePicker.openPicker({
                width: 300,
                height: 300,
                cropping: true
            }).then(image => {
                
            })
    
    //从相册中选择多张图片
    ImagePicker.openPicker({
                multiple: true
            }).then(images => {
                console.log(images);
            });
    
    //拍照
    ImagePicker.openCamera({
                width: 300,
                height: 400,
                cropping: true
            }).then(image => {
                console.log(image);
            });
    
    //返回的资源对象(images):
    path(string):图片地址
    data(base64):图片base64格式数据流
    mime(string):图片格式
    width(number):图片宽度
    height(number):图片高度
    size(number):图片大小
    

    2:xcode添加库和设置相册拍照权限

    找到linked frameworks and libraries导入库:
    RSKImageCropper.framework
    QBImagePicker.framework
    
    plist文件设置权限
    访问相机:NSCameraUsageDescription   
    访问相册:NSPhotoLibraryUsageDescription
    
    使用效果1:
    Untitled16.gif

    3:上传图片

    上传图片的方法
    //url:params对象包含图片本地路径path
    _uploadImage =(url, params)=> {
            return new Promise(function (resolve, reject) {
                var ary = params.path.split('/');
                console.log('2222222' + ary);
                //设置formData数据
                let formData = new FormData();
                let file = {uri: params.path, type: 'multipart/form-data', name: ary[ary.length-1]};
                formData.append("file", file);
                //fetch post请求
                fetch('http://localhost:8010/birds/' + url, {
                    method: 'POST',
                    //设置请求头,请求体为json格式,identity为未压缩
                    headers: {
                        'Content-Type': 'application/json',
                        'Content-Encoding': 'identity'
                    },
                    body: JSON.stringify(formData),
                }).then((response) => response.json())
                    .then((responseData)=> {
                        console.log('uploadImage', responseData);
                        resolve(responseData);
                    })
                    .catch((err)=> {
                        console.log('err', err);
                        reject(err);
                    });
                });
        };
    
    调用上传图片方法
    //_imageObj为返回的资源对象(images)
    _beginUpImage =()=> {
            let params = {
                path:  this._imageObj['path'],    //本地文件地址
            };
            this._uploadImage('uploadImage', params)
                .then( res=>{
                    console.log('success');
                }).catch( err=>{
                //请求失败
                console.log('flied');
            })
        };
    

    完整的reactNative代码:

    import ImagePicker from 'react-native-image-crop-picker';
    import React, { Component } from 'react';
    import {
        AppRegistry,
        View,
        Text,
        TouchableOpacity,
        Image
    } from 'react-native';
    
    class RNCameraView extends Component {
       //初始化一个对象,path本地路径
        _imageObj = {
            path: '/Users/kk/XueXireactNativeDeDaiMa/SampleAppMovies/image/d11.png'
        };
    
        constructor(props) {
            super(props);
            this.state = {
                imageUrl: require('./image/d11.png')
            }
        }
        render() {
            return (
                <View style={{flex: 1, backgroundColor: '#aaffaa', alignItems: 'center', justifyContent: 'center'}}>
                    <Image style={{width: 300, height: 300}}
                           source={this.state.imageUrl}/>
    
                    <TouchableOpacity style={{width: 80, height: 60, backgroundColor: '#ffaaaa', marginTop: 20}}
                                      onPress={this._openPicker}>
                        <Text>从相册中选择单张图片</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: 80, height: 60, backgroundColor: '#ffaaaa', marginTop: 20}}
                                      onPress={this._openTwoPicker}>
                        <Text>从相册中选择多张图片</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: 80, height: 60, backgroundColor: '#ffaaaa', marginTop: 20}}
                                      onPress={this._openCamera}>
                        <Text>拍照</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: 80, height: 60, backgroundColor: '#ffaa00', marginTop: 20}}
                                      onPress={this._beginUpImage}>
                        <Text>上传图片</Text>
                    </TouchableOpacity>
                </View>
            )
        }
    
        _beginUpImage =()=> {
            let params = {
                path:  this._imageObj['path'],    //本地文件地址
            };
            this.uploadImage('uploadImage', params)
                .then( res=>{
                    console.log('success');
                }).catch( err=>{
                //请求失败
                console.log('flied');
            })
        };
    
        uploadImage =(url, params)=> {
            return new Promise(function (resolve, reject) {
                var ary = params.path.split('/');
                console.log('2222222' + ary);
                let formData = new FormData();
                let file = {uri: params.path, type: 'multipart/form-data', name: ary[ary.length-1]};
                formData.append("file", file);
    
                fetch('http://localhost:8010/birds/' + url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Content-Encoding': 'identity'
                    },
                    body: JSON.stringify(formData),
                }).then((response) => response.json())
                    .then((responseData)=> {
                        console.log('uploadImage', responseData);
                        resolve(responseData);
                    })
                    .catch((err)=> {
                        console.log('err', err);
                        reject(err);
                    });
                });
        };
    
        //从相册中选择单张图片:
        _openPicker =()=> {
            ImagePicker.openPicker({
                width: 300,
                height: 300,
                cropping: true
            }).then(image => {
                console.log("111111" + image['data']);
                this.setState({
                    imageUrl: {uri: image['path']}
                });
                this._imageObj = image;
            })
        };
        //从相册中选择多张图片:
        _openTwoPicker =()=> {
            ImagePicker.openPicker({
                multiple: true
            }).then(images => {
                console.log(images);
            });
        };
        //拍照:
        _openCamera =()=> {
            ImagePicker.openCamera({
                width: 300,
                height: 400,
                cropping: true
            }).then(image => {
                console.log(image);
            });
        };
    }
    AppRegistry.registerComponent('RNCameraView', ()=>RNCameraView);
    

    4:nodejs服务端接收数据

    使用express框架,并添加body-parser依赖
    var express = require('express');
    var app = express();
    //解析请求体body
    var bodyParser = require('body-parser');
    //fs读取和写入文件
    var fs = require('fs');
    //解析请求体格式
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    //设置路由
    app.post('/uploadImage', function (req, res) {
        console.log('Content-Type====' + req.get('Content-Type'));
        var jsonBody = req.body;
        //解析jsonBody
        var file = jsonBody['_parts'][0][1];
    
        console.log('jsonBody=====' + JSON.stringify(jsonBody) + 'file====' + JSON.stringify(file));
    
        if(Object.keys(req.body).length<=0) {
            console.log('没有提交任何post参数');
        }
    
        var response;
        //设置写入文件的路径
        var des_file = __dirname + '/pubilc/images/' + file['name'];
    
        //读取文件地址
        fs.readFile(file['uri'], function (err, data) {
            //开始写入文件
            fs.writeFile(des_file, data, function (err) {
                if(err) {
                    console.log(err);
                    response = err;
                }else {
                    response = {
                        message: 'File upload successfully',
                        fileName: file['name']
                    }
                }
                console.log(response);
                res.end(JSON.stringify(response));
            })
        })
    });
    

    上传图片效果:

    点击上传图片服务端得到数据:
    9D1029AB-6425-44DB-96D6-1A4A6E1C9463.png
    app端收到服务端返回数据:
    19D33404-B4AC-49A5-B58C-F720DA63BF73.png

    相关文章

      网友评论

      • d6a908adeddd:请问裁剪图片中底部按钮 是choose 怎么变成中文,作者说不打算支持多语言
      • 无神:我的按照流程走到最后了,报了 “React/RCTDefines.h' file not found”的错误,请问您当时是如何解决的?
      • haisonLIN:你好,请问如果选择完图片就直接执行上传图片,请问这样应该怎么实现
        haisonLIN:@煎包小混沌 先谢谢你,因为是只菜鸡,请问具体代码是怎么写来的:flushed:
        煎包小混沌:@haisonLIN //从相册中选择单张图片:
        _openPicker =()=> {
        ImagePicker.openPicker({
        width: 300,
        height: 300,
        cropping: true
        }).then(image => {
        console.log("111111" + image['data']);
        this.setState({
        imageUrl: {uri: image['path']}
        });
        this._imageObj = image;
        })
        };
        这个地方选择图片回调,直接调用上传的接口就可以了
      • YY_Lee:请问你是安装GitHub上的文档集成的吗,我集成之后报错'React/RCTDefines.h' file not found
        煎包小混沌:@Gradient 好的,解决了就好
        YY_Lee:@无神 手动导入这个库
        无神:@Gradient 我的也报了同样的错误,仔细检查了代码,是因为执行了 react-native link react-native-image-crop-picker,这个命令,在xcode中自动生成了两个文件,然后报了您说的那个错,您的最后是如何解决的?

      本文标题:React-Native 使用react-native-imag

      本文链接:https://www.haomeiwen.com/subject/cldalxtx.html