1:先學(xué)習(xí)react-native-image-crop-picke
的使用方法
導(dǎo)入 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';
調(diào)用 react-native-image-crop-picke
的方法
//從相冊(cè)中選擇單張圖片
//cropping是否切割
ImagePicker.openPicker({
width: 300,
height: 300,
cropping: true
}).then(image => {
})
//從相冊(cè)中選擇多張圖片
ImagePicker.openPicker({
multiple: true
}).then(images => {
console.log(images);
});
//拍照
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log(image);
});
//返回的資源對(duì)象(images):
path(string):圖片地址
data(base64):圖片base64格式數(shù)據(jù)流
mime(string):圖片格式
width(number):圖片寬度
height(number):圖片高度
size(number):圖片大小
2:xcode添加庫和設(shè)置相冊(cè)拍照權(quán)限
找到linked frameworks and libraries導(dǎo)入庫:
RSKImageCropper.framework
QBImagePicker.framework
plist文件設(shè)置權(quán)限
訪問相機(jī):NSCameraUsageDescription
訪問相冊(cè):NSPhotoLibraryUsageDescription
使用效果1:
3:上傳圖片
上傳圖片的方法
//url:params對(duì)象包含圖片本地路徑path
_uploadImage =(url, params)=> {
return new Promise(function (resolve, reject) {
var ary = params.path.split('/');
console.log('2222222' + ary);
//設(shè)置formData數(shù)據(jù)
let formData = new FormData();
let file = {uri: params.path, type: 'multipart/form-data', name: ary[ary.length-1]};
formData.append("file", file);
//fetch post請(qǐng)求
fetch('http://localhost:8010/birds/' + url, {
method: 'POST',
//設(shè)置請(qǐng)求頭锡移,請(qǐng)求體為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);
});
});
};
調(diào)用上傳圖片方法
//_imageObj為返回的資源對(duì)象(images)
_beginUpImage =()=> {
let params = {
path: this._imageObj['path'], //本地文件地址
};
this._uploadImage('uploadImage', params)
.then( res=>{
console.log('success');
}).catch( err=>{
//請(qǐng)求失敗
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 {
//初始化一個(gè)對(duì)象,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>從相冊(cè)中選擇單張圖片</Text>
</TouchableOpacity>
<TouchableOpacity style={{width: 80, height: 60, backgroundColor: '#ffaaaa', marginTop: 20}}
onPress={this._openTwoPicker}>
<Text>從相冊(cè)中選擇多張圖片</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=>{
//請(qǐng)求失敗
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);
});
});
};
//從相冊(cè)中選擇單張圖片:
_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;
})
};
//從相冊(cè)中選擇多張圖片:
_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服務(wù)端接收數(shù)據(jù)
使用express框架,并添加body-parser依賴
var express = require('express');
var app = express();
//解析請(qǐng)求體body
var bodyParser = require('body-parser');
//fs讀取和寫入文件
var fs = require('fs');
//解析請(qǐng)求體格式
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//設(shè)置路由
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參數(shù)');
}
var response;
//設(shè)置寫入文件的路徑
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));
})
})
});
上傳圖片效果:
點(diǎn)擊上傳圖片服務(wù)端得到數(shù)據(jù):
9D1029AB-6425-44DB-96D6-1A4A6E1C9463.png
app端收到服務(wù)端返回?cái)?shù)據(jù):
19D33404-B4AC-49A5-B58C-F720DA63BF73.png