[英]how to convert base64 to Image in react native
我是新来的反应本地人。 我创建了一个表格。 我在其中添加 3 个图像和 1 个数字签名。 然后我将这些图像发送到服务器。 但我收到 base64 响应。 那么如何将 base64 响应转换为图像。 然后使用 formdata multipart 将此图像发送到服务器。
这是我的代码
saveSign = () => {
this.sign.current.saveImage();
};
resetSign = () => {
this.sign.current.resetImage();
};
_onSaveEvent = (result) => {
const imagePath = result;
console.log("Response = "+JSON.stringify(imagePath));
this.setState({image: imagePath})
};
_onDragEvent = () => {
// This callback will be called when the user enters signature
console.log('dragged');
};
<SignatureCapture
style={styles.signature}
ref={this.sign}
onSaveEvent={this._onSaveEvent}
onDragEvent={this._onDragEvent}
showNativeButtons={false}
// saveImageFileInExtStorage={true}
showTitleLabel={false}
viewMode={'portrait'}
/>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.saveSign}>
<Text>Save</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.resetSign}>
<Text>Reset</Text>
</TouchableHighlight>
这是我的完整代码
import React, { Component , createRef } from "react";
import {
Dimensions,
Image,
StyleSheet,
ScrollView,
TouchableOpacity,
View,
Alert,
ListView,
Text, Button, TouchableHighlight, TextInput
} from "react-native";
// import { Card, Badge, Button, Block, Text } from "../components";
import AsyncStorage from "@react-native-community/async-storage"
import { Container, Header, Content, Card, CardItem, Body, } from 'native-base';
import { BackHandler } from 'react-native';
import { heightPercentageToDP } from "react-native-responsive-screen";
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { PermissionsAndroid } from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import { getIsDrawerOpenFromState } from "@react-navigation/drawer";
import SignatureCapture from 'react-native-signature-capture';
const { width } = Dimensions.get("window");
export default class Kyc extends Component{
constructor(props) {
super(props);
const {data} = this.props.route.params
const PAND = data.kyc_information_data[0] ? data.kyc_information_data[0].pan_card_number : ''
const GSTD = data.kyc_information_data[0] ? data.kyc_information_data[0].gstin_number : ''
const ADHD = data.kyc_information_data[0] ? data.kyc_information_data[0].aadhar_card_number : ''
this.state = {
base64data:'',
base64:null,
PAN:PAND,
GST:GSTD,
ADH:ADHD,
resourcePath: {},
signature: null,
singleFile:null,
fileUri:null,
imageArray:{
PAN: null,
ADH: null,
ADH1: null,
},
singleFilePAN:null,
singleFileADH:null,
singleFileADH1:null,
singleFileSIGN:null,
base64Icon:null,
image:null
};
this.ref = React.createRef();
this.sign = React.createRef();
}
saveSign = () => {
this.sign.current.saveImage();
};
resetSign = () => {
this.sign.current.resetImage();
};
_onSaveEvent = (result) => {
// const [imagePath,setImagePath ] = useState(result.pathName);
//result.encoded - for the base64 encoded png
//result.pathName - for the file path name
alert('Signature Captured Successfully');
// console.log("response ahgedfasfd"+result.pathName);
const imagePath = result;
console.log("Response = "+JSON.stringify(imagePath));
this.setState({base64data: result})
console.log("ye hehehehhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"+ this.state.base64data)
var base64Icon = `data:image/png;base64,${this.state.base64data}`;
this.setState({base64: base64Icon})
this.setState({image: imagePath})
};
_onDragEvent = () => {
// This callback will be called when the user enters signature
console.log('dragged');
};
uploadImage = () => {
AsyncStorage.multiGet(["application_id", "created_by"]).then(response => {
const { leadTagNumber } = this.props.route.params;
if ( this.state.singleFilePAN != null && this.state.singleFileADH != null && this.state.singleFileADH1 != null )
{
const formData = new FormData();
// formData.append('phpid',phpid);
formData.append('lead_tag_number',leadTagNumber);
formData.append('pan_card_number', this.state.PAN);
formData.append('gstin_number', this.state.GST);
formData.append('aadhar_card_number', this.state.ADH);
formData.append('idfy_pan_card_status', "Done");
formData.append('idfy_aadhar_card_status',"Done");
formData.append('entry_sorce', "App");
formData.append('created_by', response[1][1]);
formData.append('application_id', response[0][1]);
formData.append('is_active', "Y");
formData.append('is_deleted', "N");
formData.append('created_time', "");
formData.append("lead_tag_number", "NAS00001");
formData.append('upload_pancard',
{
uri: this.state.singleFilePAN,
name: 'pancardImage.jpg',
type: 'image/*'
}
);
formData.append('upload_aadhar',
{
uri: this.state.singleFileADH,
name: 'upload_aadhar.jpg',
type: 'image/*'
}
);
formData.append('upload_aadhar_second',
{
uri: this.state.singleFileADH1,
name: 'upload_aadhar_second.jpg',
type: 'image/*'
}
);
formData.append('digital_signature',
{
uri: this.state.image,
name: 'digital_signature.jpg',
type: 'image/*'
}
);
console.log(JSON.stringify(formData))
fetch('https://nasdigital.tech/Android_API_CI/upload_multipart_data',
{
method: 'post',
body : formData,
headers: {
'Content-Type': 'multipart/form-data;',
},
}
)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
})
}
requestCameraPermissionpan = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "App Camera Permission",
message:"App needs access to your camera ",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchCamera(options, (res) => {
console.log('Response = ', res);
if (res.didCancel) {
console.log('User cancelled image picker');
} else if (res.error) {
console.log('ImagePicker Error: ', res.error);
} else if (res.customButton) {
console.log('User tapped custom button: ', res.customButton);
alert(res.customButton);
} else {
const source = { uri: res.uri };
console.log('response', res.uri);
const newImageArray = this.state.imageArray;
newImageArray.PAN = res.uri
this.setState({imageArray : {...newImageArray}})
this.setState({
filePath: res,
fileData: res.data,
fileUri: res.uri,
singleFilePAN: newImageArray.PAN,
});
}
})
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
requestCameraPermissionadh1 = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "App Camera Permission",
message:"App needs access to your camera ",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchCamera(options, (res) => {
console.log('Response = ', res);
if (res.didCancel) {
console.log('User cancelled image picker');
} else if (res.error) {
console.log('ImagePicker Error: ', res.error);
} else if (res.customButton) {
console.log('User tapped custom button: ', res.customButton);
alert(res.customButton);
} else {
const source = { uri: res.uri };
console.log('response', res.uri);
const newImageArray = this.state.imageArray;
newImageArray.ADH = res.uri
this.setState({imageArray : {...newImageArray}})
this.setState({
filePath: res,
fileData: res.data,
fileUri: res.uri,
singleFileADH: newImageArray.ADH,
});
}
})
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
requestCameraPermissionadh2 = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "App Camera Permission",
message:"App needs access to your camera ",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchCamera(options, (res) => {
console.log('Response = ', res);
if (res.didCancel) {
console.log('User cancelled image picker');
} else if (res.error) {
console.log('ImagePicker Error: ', res.error);
} else if (res.customButton) {
console.log('User tapped custom button: ', res.customButton);
alert(res.customButton);
} else {
const source = { uri: res.uri };
console.log('response', res.uri);
const newImageArray = this.state.imageArray;
newImageArray.ADH1 = res.uri
this.setState({imageArray : {...newImageArray}})
this.setState({
filePath: res,
fileData: res.data,
fileUri: res.uri,
singleFileADH1: newImageArray.ADH1
});
}
})
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
handlePAN = (text) => {
// this.setState({ DistributorError: '' })
this.setState({ PAN: text })
}
handleGST = (text) => {
// this.setState({ DistributorCodeError: '' })
this.setState({ GST: text })
}
handleADH = (text) => {
// this.setState({ SalesCodeError: '' })
this.setState({ ADH: text })
}
render(){
return(
<View style={{ flexDirection: 'column',backgroundColor:"yellow"}}>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-evenly',
marginTop:hp('5')
}}>
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TextInput
onChangeText={this.handlePAN}
defaultValue={this.state.PAN}
style={{width:wp('70'), height: hp('5'), color: 'black', borderWidth: 1, borderRadius: 10,borderColor: "black",
backgroundColor:"white",fontSize:16}}></TextInput>
<Image source={{uri: this.state.imageArray.PAN}} style={{width: 50, height: 50}} />
{/* </View> */}
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TouchableOpacity onPress={this.requestCameraPermissionpan} style={{width:wp('15'), height: hp('5'),backgroundColor:"orange",borderWidth: 1, borderRadius: 10,borderColor: "black"}}>
<Text style={{alignSelf:"center", paddingTop:hp('1')}}>Pancard</Text>
</TouchableOpacity>
{/* </View> */}
</View>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-evenly',
marginTop:hp('8')
}}>
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TextInput
onChangeText={this.handleGST}
defaultValue={this.state.GST}
style={{width:wp('70'), height: hp('5'), color: 'black', borderWidth: 1, borderRadius: 10,borderColor: "black",
backgroundColor:"white",fontSize:16}}></TextInput>
<Image source={{uri: this.state.imageArray.ADH}} style={{width: 50, height: 50}} />
{/* </View> */}
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TouchableOpacity onPress={this.requestCameraPermissionadh1} style={{width:wp('15'), height: hp('5'),backgroundColor:"orange",borderWidth: 1, borderRadius: 10,borderColor: "black"}}>
<Text style={{alignSelf:"center", paddingTop:hp('1')}}>Aadhar</Text>
</TouchableOpacity>
{/* </View> */}
</View>
<View style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-evenly',
marginTop:hp('8')
}}>
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TextInput
onChangeText={this.handleADH}
defaultValue={this.state.ADH}
style={{width:wp('70'), height: hp('5'), color: 'black', borderWidth: 1, borderRadius: 10,borderColor: "black",
backgroundColor:"white",fontSize:16}}></TextInput>
<Image source={{uri: this.state.imageArray.ADH1}} style={{width: 50, height: 50}} />
{/* </View> */}
{/* <View style={{ backgroundColor: 'powderblue'}}> */}
<TouchableOpacity onPress={this.requestCameraPermissionadh2} style={{width:wp('15'), height: hp('5'),backgroundColor:"orange",borderWidth: 1, borderRadius: 10,borderColor: "black"}}>
<Text style={{alignSelf:"center", paddingTop:hp('1')}}>GST</Text>
</TouchableOpacity>
{/* </View> */}
</View>
{/* <View style={{marginTop:hp('10'), alignSelf:"center"}}>
<SignatureCapture
style={styles.signature}
ref={this.sign}
onSaveEvent={this._onSaveEvent}
onDragEvent={this._onDragEvent}
showNativeButtons={false}
showTitleLabel={false}
viewMode={'portrait'}
/>
</View> */}
{/* <View style={{flex:1, backgroundColor:"red", marginTop:hp('10')}}><Text>Name</Text></View> */}
{/* <SignatureCapture
style={styles.signature}
ref={this.sign}
onSaveEvent={this._onSaveEvent}
onDragEvent={this._onDragEvent}
showNativeButtons={false}
showTitleLabel={false}
viewMode={'portrait'}
/>
<View style={{flexDirection: 'row'}}>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.saveSign}>
<Text>Save</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.resetSign}>
<Text>Reset</Text>
</TouchableHighlight>
</View>
*/}
<View style={{marginTop:hp('8'), alignSelf:"center"}}>
{/* <TextInput style={{marginTop:hp('10'), alignSelf:"center",
alignSelf: "center",
marginTop:hp('5'),
width: 330,
height: hp('30'),
width:wp('80'),
paddingHorizontal: 10,
borderRadius: 1,
borderWidth: 1,
borderRadius: 10,
borderColor: "#FF8C00",
backgroundColor: 'rgb(255, 252, 252)',}}><Text>Dahtvjyukn,</Text></TextInput> */}
<SignatureCapture
style={styles.signature}
ref={this.sign}
onSaveEvent={this._onSaveEvent}
onDragEvent={this._onDragEvent}
showNativeButtons={false}
// saveImageFileInExtStorage={true}
showTitleLabel={false}
viewMode={'portrait'}
/>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.saveSign}>
<Text>Save</Text>
</TouchableHighlight>
<TouchableHighlight
style={styles.buttonStyle}
onPress={
this.resetSign}>
<Text>Reset</Text>
</TouchableHighlight>
<Image style={{width: 100, height: 50, borderWidth: 1, borderColor: 'red'}} source={{uri: this.state.base64}}/>
</View>
<TouchableOpacity onPress={this.uploadImage} style={{alignSelf:"center", width:wp('60'), height: hp('6'),backgroundColor:"orange",
borderWidth: 1, borderRadius: 10,borderColor: "black",marginTop:hp('10'),}}>
<Text style={{alignSelf:"center", paddingTop:hp('1.5')}}>GST</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
inputStyle: {
flex: 1,
color: 'black',
height:hp('5'),
width:wp('1'),
// paddingLeft: 15,
// paddingRight: 15,
borderWidth: 1,
borderRadius: 10,
borderColor: "black",
backgroundColor:"white",
fontSize:16
},
container: {
flex: 1,
justifyContent:"center",
alignSelf:"center"
},
profileImgContainer: {
marginTop: 20,
marginLeft: 18,
height: 110,
width: 110,
borderRadius: 60,
},
profileImg: {
height: 110,
width: 110,
borderRadius: 60,
},
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
},
nex: {
backgroundColor: "orange",
height: hp('20%'),
width: "100%"
},
image: {
// resizeMode: 'contain',
height: 160,
width: 160,
alignSelf: 'center',
borderWidth: 1,
borderRadius: 10,
borderColor: "black",
// height:150,
// width:"45%",
marginTop: 70,
},
card: {
borderRadius: 6,
elevation: 3,
backgroundColor: "white",
shadowColor: "#333",
shadowOffset: { width: 1, height: 1 },
shadowOpacity: 0.3,
shadowRadius: 2,
marginHorizontal: 4,
marginVertical: 6,
height: hp('30%'),
width: wp('45'),
backgroundColor: "orange"
},
cardContent: {
marginHorizontal: 18,
marginVertical: 10,
},
cards: {
borderRadius: 8,
elevation: 5,
backgroundColor: "white",
shadowColor: "#333",
shadowOffset: { width: 1, height: 1 },
shadowOpacity: 0.3,
shadowRadius: 8,
marginHorizontal: 4,
marginVertical: 6,
height: hp('30%'),
width: wp('45'),
},
cardx: {
borderRadius: 6,
elevation: 3,
backgroundColor: "white",
shadowColor: "#333",
shadowOffset: { width: 1, height: 1 },
shadowOpacity: 0.3,
shadowRadius: 2,
marginHorizontal: 4,
marginVertical: 6,
height: hp('10%'),
width: wp('45%'),
backgroundColor: "orange",
marginBottom: 0
},
cardContents: {
marginHorizontal: 18,
marginVertical: 10,
},
profileImgContainers: {
marginTop: 20,
height: 120,
width: 120,
borderRadius: 60,
},
profileImgs: {
height: 120,
width: 120,
borderRadius: 60,
backgroundColor: "orange"
},
signature: {
// flex: 1,
// borderColor: 'black',
// borderWidth: 2,
// height:400,
// width:300,
// marginTop:200,
marginTop:hp('10'), alignSelf:"center",
alignSelf: "center",
marginTop:hp('5'),
width: 330,
height: hp('30'),
width:wp('80'),
paddingHorizontal: 10,
borderRadius: 1,
borderWidth: 1,
borderRadius: 10,
borderColor: "#FF8C00",
},
});
请忽略这一点。 我是新来的反应本地人。 我创建了一个表格。 我在其中添加 3 个图像和 1 个数字签名。 然后我将这些图像发送到服务器。 但我收到 base64 响应。 那么如何将 base64 响应转换为图像。 然后使用 formdata multipart 将此图像发送到服务器。我是本机反应的新手。 我创建了一个表格。 我在其中添加 3 个图像和 1 个数字签名。 然后我将这些图像发送到服务器。 但我收到 base64 响应。 那么如何将 base64 响应转换为图像。 然后使用 formdata multipart 将此图像发送到服务器。我是本机反应的新手。 我创建了一个表格。 我在其中添加 3 个图像和 1 个数字签名。 然后我将这些图像发送到服务器。 但我收到 base64 响应。 那么如何将 base64 响应转换为图像。 然后使用 formdata multipart 将此图像发送到服务器。我是本机反应的新手。 我创建了一个表格。 我在其中添加 3 个图像和 1 个数字签名。 然后我将这些图像发送到服务器。 但我收到 base64 响应。 那么如何将 base64 响应转换为图像。 然后使用 formdata multipart 将此图像发送到服务器。
它还提供filePath
_onSaveEvent(result) {
//result.encoded - for the base64 encoded png
//result.pathName - for the file path name
console.log(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.