本机反应:无法将文件上传到服务器:网络请求失败
react native: unable to upload file to server : Network request failed
我正在尝试向北方上传文件,但是文件没有发送到服务器并且反应本机在控制台中抛出错误:网络请求失败。
我试图通过 Postman 测试 api。文件上传成功。我的选择结束了。我很乐意提示我做错了什么。
代码上传页面:
// Import React
import React, { useState } from 'react';
// Import core components
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
// Import Document Picker
import DocumentPicker from 'react-native-document-picker';
const UploadPage = ({ navigation }) => {
const [singleFile, setSingleFile] = useState(null);
const uploadImage = async () => {
// Check if any file is selected or not
if (singleFile != null) {
// If file selected then create FormData
const fileToUpload = singleFile;
const data = new FormData();
data.append('file_attachment', fileToUpload);
// Please change file upload URL
let res = await fetch('http://10.0.2.2:8080/upload.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
);
let responseJson = await response.json(); {
alert('Upload Successful');
console.log('responseJson ' + responseJson);
}
} else {
// If no file selected the show alert
alert('Please Select File first');
console.log('Fucking Error: ' + error);
}
};
const selectFile = async () => {
// Opening Document Picker to select one file
try {
const res = await DocumentPicker.pick({
// Provide which type of file you want user to pick
type: [DocumentPicker.types.allFiles],
// There can me more options as well
// DocumentPicker.types.allFiles
// DocumentPicker.types.images
// DocumentPicker.types.plainText
// DocumentPicker.types.audio
// DocumentPicker.types.pdf
});
// Printing the log realted to the file
console.log('res : ' + JSON.stringify(res));
// Setting the state to show single file attributes
setSingleFile(res);
} catch (err) {
setSingleFile(null);
// Handling any exception (If any)
if (DocumentPicker.isCancel(err)) {
// If user canceled the document selection
alert('Canceled');
} else {
// For Unknown Error
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
return (
<View style={styles.mainBody}>
<View style={{ alignItems: 'center' }}>
</View>
{/*Showing the data of selected Single file*/}
{singleFile != null ? (
<Text style={styles.textStyle}>
File Name: {singleFile.name ? singleFile.name : ''}
{'\n'}
Type: {singleFile.type ? singleFile.type : ''}
{'\n'}
</Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={selectFile}>
<Text style={styles.buttonTextStyle}>Select File</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={uploadImage}>
<Text style={styles.buttonTextStyle}>Upload File</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
mainBody: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
buttonStyle: {
backgroundColor: '#307ecc',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#307ecc',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 15,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
textStyle: {
backgroundColor: '#fff',
fontSize: 15,
marginTop: 16,
marginLeft: 35,
marginRight: 35,
textAlign: 'center',
},
});
export default UploadPage;
代码PHPAPI:
<?php
// Type your website name or domain name here.
$domain_name = "http://localhost:8080/" ;
// Image uploading folder.
$target_dir = "uploads";
// Generating random image name each time so image name will not be same .
$target_dir = $target_dir . "/" .rand() . "_" . time() . ".jpeg";
// Receiving image tag sent from application.
// Receiving image sent from Application
if(move_uploaded_file($_FILES['filetoupload']['tmp_name'], $target_dir)){
// Adding domain name with image random name.
$target_dir = $domain_name . $target_dir ;
// Inserting data into MySQL database.
$MESSAGE = "Image Uploaded Successfully." ;
// Printing response message on screen after successfully inserting the image .
echo json_encode($MESSAGE);
}
?>
控制台日志:
选择文件后,“res”会显示在控制台中。
发送时显示“网络请求失败”
When sending a file via PostMan, it is successfully uploaded to the server.
尝试更改此行
data.append('data', fileToUpload);
和
data.append("data", {type: 'image/jpg', uri:fileToUpload, name:fileToUpload});
我正在尝试向北方上传文件,但是文件没有发送到服务器并且反应本机在控制台中抛出错误:网络请求失败。 我试图通过 Postman 测试 api。文件上传成功。我的选择结束了。我很乐意提示我做错了什么。
代码上传页面:
// Import React
import React, { useState } from 'react';
// Import core components
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
// Import Document Picker
import DocumentPicker from 'react-native-document-picker';
const UploadPage = ({ navigation }) => {
const [singleFile, setSingleFile] = useState(null);
const uploadImage = async () => {
// Check if any file is selected or not
if (singleFile != null) {
// If file selected then create FormData
const fileToUpload = singleFile;
const data = new FormData();
data.append('file_attachment', fileToUpload);
// Please change file upload URL
let res = await fetch('http://10.0.2.2:8080/upload.php',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
);
let responseJson = await response.json(); {
alert('Upload Successful');
console.log('responseJson ' + responseJson);
}
} else {
// If no file selected the show alert
alert('Please Select File first');
console.log('Fucking Error: ' + error);
}
};
const selectFile = async () => {
// Opening Document Picker to select one file
try {
const res = await DocumentPicker.pick({
// Provide which type of file you want user to pick
type: [DocumentPicker.types.allFiles],
// There can me more options as well
// DocumentPicker.types.allFiles
// DocumentPicker.types.images
// DocumentPicker.types.plainText
// DocumentPicker.types.audio
// DocumentPicker.types.pdf
});
// Printing the log realted to the file
console.log('res : ' + JSON.stringify(res));
// Setting the state to show single file attributes
setSingleFile(res);
} catch (err) {
setSingleFile(null);
// Handling any exception (If any)
if (DocumentPicker.isCancel(err)) {
// If user canceled the document selection
alert('Canceled');
} else {
// For Unknown Error
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
return (
<View style={styles.mainBody}>
<View style={{ alignItems: 'center' }}>
</View>
{/*Showing the data of selected Single file*/}
{singleFile != null ? (
<Text style={styles.textStyle}>
File Name: {singleFile.name ? singleFile.name : ''}
{'\n'}
Type: {singleFile.type ? singleFile.type : ''}
{'\n'}
</Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={selectFile}>
<Text style={styles.buttonTextStyle}>Select File</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={uploadImage}>
<Text style={styles.buttonTextStyle}>Upload File</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
mainBody: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
buttonStyle: {
backgroundColor: '#307ecc',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#307ecc',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 15,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
textStyle: {
backgroundColor: '#fff',
fontSize: 15,
marginTop: 16,
marginLeft: 35,
marginRight: 35,
textAlign: 'center',
},
});
export default UploadPage;
代码PHPAPI:
<?php
// Type your website name or domain name here.
$domain_name = "http://localhost:8080/" ;
// Image uploading folder.
$target_dir = "uploads";
// Generating random image name each time so image name will not be same .
$target_dir = $target_dir . "/" .rand() . "_" . time() . ".jpeg";
// Receiving image tag sent from application.
// Receiving image sent from Application
if(move_uploaded_file($_FILES['filetoupload']['tmp_name'], $target_dir)){
// Adding domain name with image random name.
$target_dir = $domain_name . $target_dir ;
// Inserting data into MySQL database.
$MESSAGE = "Image Uploaded Successfully." ;
// Printing response message on screen after successfully inserting the image .
echo json_encode($MESSAGE);
}
?>
控制台日志:
选择文件后,“res”会显示在控制台中。 发送时显示“网络请求失败”
When sending a file via PostMan, it is successfully uploaded to the server.
尝试更改此行
data.append('data', fileToUpload);
和
data.append("data", {type: 'image/jpg', uri:fileToUpload, name:fileToUpload});