React-native-image-picker is a third-party library that integrates the capabilities of cameras and albums because it is relatively simple to use and is loved by front-end developers. React-native-image-picker Use
1, first, install the plugin.
NPM Install React-native-image-picker@latest--save
2, configure the Android and iOS platforms separately
# # Android Platform configuration
1, add the following code in the Android/settings.gradle file:
Include ': React-native-image-picker '
project (': React-native-image-picker '). ProjectDir = new File (Settingsdir, ' .. /node_modules/react-native-image-picker/android ')
2, add the following code to the dependencies of the Android/app/build.gradle file:
Compile project (': React-native-image-picker ')
3, add permissions in the Androidmanifest.xml file:
<uses-permission android:name= "Android.permission.CAMERA"/>
<uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>
4, and finally add the following code in the Mainapplication.java file:
Import Com.imagepicker.ImagePickerPackage;
New Imagepickerpackage ()
This way, the Android environment is configured. iOS Platform Configuration
1, open Xcode Open the project, click the root directory, the right button to select Add files to ' XXX ', select the project in the path of the file can be: node_modules-> react-native-image-picker-> iOS- > select Rnimagepicker.xcodeproj
2, add success after the use of link command: React-native link react-native-image-picker.
3, open the project to use build phases-> Link Binary and libraries to add RNIMAGEPICKER.A to the project dependencies.
4, for iOS 10+ devices, you need to configure Nsphotolibraryusagedescription and nscamerausagedescription in Info.plist.
React-native-image-picker Sample
For the convenience of project use, we encapsulate it as a component camerabutton.js. The code is as follows:
Import react from ' react ' import {touchableopacity, StyleSheet, Platform, Activityindicator, View,
Text, toastandroid} from ' react-native ' var imagepicker = require (' React-native-image-picker ');
Import Icon from ' react-native-vector-icons/ionicons '; Const OPTIONS = {title: ' Choose Picture ', Cancelbuttontitle: ' Cancel ', Takephotobuttontitle: ' Photograph ', Choosefromlibraryb
Uttontitle: ' Photo gallery ', Cameratype: ' Back ', mediatype: ' Photo ', videoquality: ' High ', durationlimit:10, maxwidth:600, maxheight:600, Aspectx:2, Aspecty:1, quality:0.8, angle:0, Allowsediting:fal
SE, Nodata:false, storageoptions: {skipbackup:true, path: ' Images '};
Class Camerabutton extends React.component {constructor (props) {super (props);
This.state = {Loading:false}} render () {const {Photos,type} = This.props;
Let the context; if (pHotos.length > 0) {context = (<view style={styles.countbox}> <text style={styles.c
Ount}>{photos.length}</text> </View>);
Return (<touchableopacity Onpress={this.showimagepicker.bind (This)} style={[this.props.style,styles.camerabtn]}> <View> <icon name= "Md-cam Era "color=" #aaa "size={34}/> {context} </View> </touchableopa
city>)} showimagepicker () {Imagepicker.showimagepicker (options, (response) => {
if (response.didcancel) {console.log (' User cancelled image picker ');
else if (response.error) {console.log (' Imagepicker error: ', response.error);
else {let source; if (Platform.os = = ' AndrOID ') {Source = {Uri:response.uri, isstatic:true}} else {sour
Ce = {uri:response.uri.replace (' file://', '), isstatic:true}} let file;
if (Platform.os = = ' Android ') {file = Response.uri}else { File = Response.uri.replace (' file://', ')} this.setstate ({loading
: true}); This.props.onFileUpload (file,response.filename| | '
Unnamed file. jpg '). Then (result=>{this.setstate ({loading:false
})
})
}
});
} Const STYLES = Stylesheet.create ({camerabtn: {padding:5}, count:{color: ' #fff ', Fontsize:12}, fullbtn:{justifycontent: ' Center ', Alignitems: ' Center ', BACKgroundcolor: ' #fff '}, countbox:{position: ' absolute ', right:-5, top:-5, Alignitem S: ' Center ', backgroundcolor: ' #34A853 ', width:16, Height:16, Borderradius:8, justif
Ycontent: ' Center '}}; Export default Camerabutton;
And then bring it in where it needs to be used.
Import Camerabutton from '. /.. /component/huar/camerabutton '
<camerabutton style={styles.camerabtn}
photos={[]}
onFileUpload={ This.onfileupload}/>
Click Upload event:
onfileupload (file, fileName) {return
This.props.uploadAvatar ({
Id:this.props.user.ID,
type: ' logo ',
obj: ' user ',
corpId:this.props.cropId
}, file, FileName}
Action Request code:
function Actions (Dispatch) {return
{
fileurl,filename) =>dispatch ( Actions.uploadavatar (params, fileurl,filename)
}}
The Uploadavatar functions in actions are as follows.
function Uploadavatar (params, FILEURL, fileName) {return
dispatch=> {return
userservice.uploadimage ( params, FILEURL, FileName)
. Then (Result=> {dispatch
({
Type:update_avatar,
Path:result.path
})
return result
})
}
//userservice.uploadimage code follows
the export function uploadimage (params, Fileurl,filename) {return
http.uploadfile (' ${config. Uploadimage} ', params, Fileurl,filename
}
The HTTP asynchronous upload image code for the UserService function is as follows:
let querystring = require (' query-string '); import Storage from './storage ' Import {Platform
From ' react-native ' const OS = platform.os;
Async function UploadFile (URL, params, fileurl,filename) {Let Access_token = await storage.getitem (' Access_token ');
Let data = new FormData ();
Data.append (' file ', {uri:fileurl, name:filename, type: ' Image/jpeg '}); Object.keys (params). ForEach ((key) => {if (params[key) instanceof Date) {data.append (key, Value.toi
Sostring ())} else {data.append (key, String (Params[key))}}); Const FetchOptions = {method: ' POST ', headers: {' Accept ': ' Application/json ', ' A Ccess_token ': Access_token?
Access_token: ', ' useragent ': OS}, Body:data}; return fetch (URL, fetchoptions). Then (CheckStatus). Then (Parsejson)}
Package Upload
If the above implementation looks more complicated, then we do the following encapsulation:
Let Common_url = ' http://192.168.1.1:8080/'; Server address Let token = '; Token function Uploadimage (url,params) {return to New Promise (function (resolve, reject) {let Formdat) returned after user login
A = new FormData ();
for (var key in params) {formdata.append (key, Params[key]);
Let file = {uri:params.path, type: ' Application/octet-stream ', Name: ' Image.jpg '};
Formdata.append ("file", file); Fetch (Common_url + URL, {method: ' POST ', headers: {' content-type ': ' MULTIPART/FO Rm-data;charset=utf-8 ', "X-access-token": Token,}, Body:formdata,}). The N ((response) => Response.json ()). Then (ResponseData) => {console.log (' uploadimage ', res
Ponsedata);
Resolve (ResponseData);
). catch ((Err) => {console.log (' err ', err);
Reject (ERR);
}); });
}
And then in the use of the place:
Let params = {
userId: ' abc12345 ',// User ID
path: ' file:///storage/emulated/0/Pictures/image.jpg ' // Local file Address
}
uploadimage (' app/uploadfile ', params)
. Then (res=>{
//Request Success
if ( Res.header.statusCode = = ' success ') {
//Here Set the server returned header StatusCode to success when the data returned successfully
Uploadimgurl = Res.body.imgurl; The server returned the address
}else{
//server returned an exception, set the server returned the exception information stored in Header.msgarray[0].desc
console.log ( RES.HEADER.MSGARRAY[0].DESC);
}
). catch (err=>{
//request failed
})
Attached: http://lib.csdn.net/article/reactnative/58022?knId=1415
Use Fetch+formdata to implement picture upload