如何在React Native中通过上载图像获取数据到php服务器
我有一个react原生项目,从文本输入中接收姓名、电子邮件、电话号码,然后将这些数据插入php服务器throw fetch api,它工作正常,但我需要让用户能够上传图像,当单击save按钮时,保存到php服务器的所有数据(姓名、电子邮件、电话号码、照片)都会抛出api,现在我使用了 “react native image picker”工作正常,但我不知道如何使用表单数据上传带有数据抛出api的图像 这是react本机代码:如何在React Native中通过上载图像获取数据到php服务器,php,api,react-native,form-data,react-native-fetch-blob,Php,Api,React Native,Form Data,React Native Fetch Blob,我有一个react原生项目,从文本输入中接收姓名、电子邮件、电话号码,然后将这些数据插入php服务器throw fetch api,它工作正常,但我需要让用户能够上传图像,当单击save按钮时,保存到php服务器的所有数据(姓名、电子邮件、电话号码、照片)都会抛出api,现在我使用了 “react native image picker”工作正常,但我不知道如何使用表单数据上传带有数据抛出api的图像 这是react本机代码: import React, { Component } from
import React, { Component } from 'react';
import {View,Text,StyleSheet,TextInput,TouchableOpacity,Image} from 'react-native';
import ViewDataUsers from './ViewDataUsers';
import ImagePicker from 'react-native-image-picker';
const options={
title:'select a photo',
takePhotoButtonTitle:'Take a Photo',
chooseFrmoLibraryButtonTitle:'Choose from Gallery',
quality:1
};
class InputUsers extends Component{
//constructor have a state that conatains the properties that will recieve the values from Text Inputes
constructor(props){
super(props)
this.state = {
TextInputName:'',
TextInputEmail:'',
TextInputPhoneNumber:'',
iamgeSource: null,
}
}
selectPhoto(){
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
let source = { uri: response.uri };
this.setState({
iamgeSource: source
});
}
});
}
//arrow function that will fire when press on save button to save data in database via API
InsertUser = ()=>{
//constant varaibles that equal propertes in state
const {TextInputName} = this.state;
const {TextInputEmail} = this.state;
const {TextInputPhoneNumber} = this.state;
//API that use fetch to input data to database via backend php script
fetch('http://192.168.1.7/tr_reactnative/insert.php',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name : TextInputName,
email: TextInputEmail,
phone_number : TextInputPhoneNumber,
})
})
.then((response) => response.json())
.then((responseJson) => {
// return responseJson
alert(responseJson);
this.props.navigation.navigate('seconde');
})
.catch((error) => {
console.error(error);
});
//alert('Pressed!!');
}
ViewUsersList = ()=>{
this.props.navigation.navigate('seconde');
}
render(){
return(
<View style ={styles.container}>
<TextInput
// value = {this.TextInputName}
placeholder = 'Enter Name'
onChangeText = {TextInputValue=>this.setState({TextInputName:TextInputValue}) }
underlineColorAndroid = 'transparent'
style = {styles.TextInputStyle}
/>
<TextInput
//value = {this.TextInputEmail}
placeholder = 'Enter E-mail'
onChangeText = {TextInputValue=>this.setState({TextInputEmail:TextInputValue}) }
underlineColorAndroid = 'transparent'
style = {styles.TextInputStyle2}
/>
<TextInput
//value = {this.TextInputPhoneNumber}
placeholder = 'Enter Phone Number'
onChangeText = {TextInputValue=>this.setState({TextInputPhoneNumber:TextInputValue}) }
underlineColorAndroid = 'transparent'
style = {styles.TextInputStyle2}
/>
<Image style={styles.image}
source={this.state.iamgeSource != null ? this.state.iamgeSource : require('./image/not_avilable.jpg')}
/>
<TouchableOpacity style = {styles.TouchableOpacityStyle} onPress={this.selectPhoto.bind(this)}>
<Text style = {styles.TextStyle}>Select Photo</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = {.4} style = {styles.TouchableOpacityStyle} onPress={this.InsertUser}>
<Text style = {styles.TextStyle}>Save</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = {.4} style = {styles.TouchableOpacityStyle} onPress={this.ViewUsersList}>
<Text style = {styles.TextStyle}>View Users</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create ({
container : {
alignItems:'center',
flex:1,
marginTop:5,
backgroundColor:'#fff'
},
TextInputStyle :{
textAlign:'center',
marginBottom:7,
width:'90%',
height:40,
borderWidth:1,
borderRadius:5,
borderColor:'#FF5722'
},
TextInputStyle2 :{
textAlign:'center',
marginBottom:7,
marginTop:20,
width:'90%',
height:40,
borderWidth:1,
borderRadius:5,
borderColor:'#FF5722'
},
TextStyle : {
color:'#fff',
textAlign:'center'
},
TouchableOpacityStyle:{
paddingTop:10,
paddingBottom:10,
marginTop:20,
borderRadius:5,
marginBottom:7,
width:'90%',
backgroundColor:'#00BCD4'
},
button:{
width:250,
height:50,
backgroundColor:"#330066"
},
text:{
color:'white',
fontSize:30,
textAlign:'center'
},
image:{
width:200,
height:200,
marginTop:30
}
});
export default InputUsers;
import React,{Component}来自'React';
从“react native”导入{View,Text,StyleSheet,TextInput,TouchableOpacity,Image};
从“/ViewDataUsers”导入ViewDataUsers;
从“react native image picker”导入ImagePicker;
常量选项={
标题:“选择照片”,
takephotobutton:“拍照”,
ChooseFrmLibrary按钮:'从库中选择',
品质:1
};
类InputUsers扩展组件{
//构造函数具有一个状态,该状态包含将从文本输入接收值的属性
建造师(道具){
超级(道具)
此.state={
TextInputName:“”,
TextInputEmail:“”,
TextInputPhoneNumber:“”,
iamgeSource:null,
}
}
选择照片(){
ImagePicker.showImagePicker(选项,(响应)=>{
log('Response=',Response);
if(response.didconcel){
log('User cancelled image picker');
}
else if(response.error){
log('ImagePicker错误:',response.Error);
}
否则{
让source={uri:response.uri};
这是我的国家({
iamgeSource:source
});
}
});
}
//当按下save(保存)按钮以通过API将数据保存到数据库中时,将触发的箭头函数
插入器=()=>{
//在状态中等于属性的常数变量
const{TextInputName}=this.state;
const{TextInputEmail}=this.state;
const{TextInputPhoneNumber}=this.state;
//API,使用fetch通过后端php脚本将数据输入数据库
取('http://192.168.1.7/tr_reactnative/insert.php',{
方法:“POST”,
标题:{
接受:'application/json',
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify({
名称:TextInputName,
电子邮件:TextInputEmail,
电话号码:TextInputPhoneNumber,
})
})
.then((response)=>response.json())
.然后((responseJson)=>{
//返回响应
警惕(回应);
this.props.navigation.navigate('seconde');
})
.catch((错误)=>{
控制台错误(error);
});
//警报('按下!!');
}
ViewUsersList=()=>{
this.props.navigation.navigate('seconde');
}
render(){
返回(
this.setState({TextInputName:TextInputValue})}
underlineColorAndroid='透明'
style={style.TextInputStyle}
/>
this.setState({TextInputEmail:TextInputValue})
underlineColorAndroid='透明'
style={style.TextInputStyle2}
/>
this.setState({TextInputPhoneNumber:TextInputValue})}
underlineColorAndroid='透明'
style={style.TextInputStyle2}
/>
选择照片
拯救
查看用户
)
}
}
const styles=StyleSheet.create({
容器:{
对齐项目:'中心',
弹性:1,
玛金托普:5,
背景颜色:“#fff”
},
文本输入样式:{
textAlign:“中心”,
marginBottom:7,
宽度:'90%',
身高:40,
边框宽度:1,
边界半径:5,
边框颜色:“#FF5722”
},
TextInputStyle2:{
textAlign:“中心”,
marginBottom:7,
玛金托普:20,
宽度:'90%',
身高:40,
边框宽度:1,
边界半径:5,
边框颜色:“#FF5722”
},
文本样式:{
颜色:“#fff”,
textAlign:“中心”
},
可触摸不透明样式:{
paddingTop:10,
填充底部:10,
玛金托普:20,
边界半径:5,
marginBottom:7,
宽度:'90%',
背景颜色:“#00BCD4”
},
按钮:{
宽度:250,
身高:50,
背景颜色:“330066”
},
正文:{
颜色:'白色',
尺寸:30,
textAlign:“中心”
},
图片:{
宽度:200,
身高:200,
玛金托普:30
}
});
导出默认输入用户;
这是php脚本:
<?php
include 'connections.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$name = $obj['name'];
$email = $obj['email'];
$phone_number = $obj['phone_number'];
if(mysqli_query($link, "INSERT INTO users(name,email, phone_number)VALUES('$name','$email','$phone_number')")){
echo json_encode('Inserted succesfully');
}else{
echo json_encode('insert faild');
}
mysqli_close($link);
要上传照片,必须使用Formdata
InsertUser = ()=>{
//constant variables that equal properties in state
const {TextInputName} = this.state;
const {TextInputEmail} = this.state;
const {TextInputPhoneNumber} = this.state;
const {iamgeSource} = this.state;
const formData = new FormData();
//Add your input data
formData.append('name', TextInputName);
formData.append('email', TextInputEmail);
formData.append('phone_number', TextInputPhoneNumber);
//Add your photo
//this, retrive the file extension of your photo
const uriPart = iamgeSource.split('.');
const fileExtension = uriPart[uriPart.length - 1];
formData.append('photo', {
uri: iamgeSource,
name: `photo.${fileExtension}`,
type: `image/${fileExtension}`
});
//API that use fetch to input data to database via backend php script
fetch('http://192.168.1.7/tr_reactnative/insert.php',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
// return responseJson
alert(responseJson);
this.props.navigation.navigate('seconde');
})
.catch((error) => {
console.error(error);
});
//alert('Pressed!!');
}
您将找到更多信息。有什么帮助吗!!????是否有任何帮助或建议?感谢您的回复,我尝试了此操作,但收到错误:imageSource.split不是FunctionOutps。Changeconst-uriPart=iamgeSource.split('.')
toconsturipart=iamgeSource.uri.split('.')
和uri:iamgeSource,
到uri:iamgeSource.uri,
。希望这次工作。文件扩展没有定义!fileExtension的声明中存在错误。我编辑它。@QuentinEtienne仅供将来参考,您不需要明确声明代码命名是按设计进行的。一般来说,变量名中的拼写更正不应该在编辑中进行,除非是通过OP进行的。回滚就足够了