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:
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