You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.7 KiB
87 lines
2.7 KiB
import React, { useEffect } from 'react';
|
|
import { View, Text, Button } from 'react-native';
|
|
import RNFS from 'react-native-fs';
|
|
import { Platform } from 'react-native';
|
|
|
|
const FileReadWriteExample = () => {
|
|
// 定义文件路径
|
|
const filePath = RNFS.DocumentDirectoryPath + '/example.txt';
|
|
|
|
// 写入文件的函数
|
|
const writeToFile = async () => {
|
|
try {
|
|
const content = 'Hello, this is a test file content.';
|
|
// 使用 RNFS.writeFile 方法写入文件
|
|
await RNFS.writeFile(filePath, content, 'utf8');
|
|
console.log('File written successfully');
|
|
} catch (error) {
|
|
console.error('Error writing file:', error);
|
|
}
|
|
};
|
|
|
|
// 读取文件的函数
|
|
const readFromFile = async () => {
|
|
try {
|
|
// 使用 RNFS.readFile 方法读取文件
|
|
const contents = await RNFS.readFile(filePath, 'utf8');
|
|
console.log('File content:', contents);
|
|
} catch (error) {
|
|
console.error('Error reading file:', error);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
// 在组件挂载时创建文件目录
|
|
RNFS.mkdir(RNFS.DocumentDirectoryPath)
|
|
.then(() => {
|
|
console.log('Directory created successfully');
|
|
})
|
|
.catch(error => {
|
|
console.error('Error creating directory:', error);
|
|
});
|
|
}, []);
|
|
|
|
const uploadFile = async () => {
|
|
const formData = new FormData();
|
|
const fileName = filePath.split('/').pop();
|
|
const fileContent = await RNFS.readFile(filePath, 'utf8');
|
|
|
|
const fileToAppend = {
|
|
// uri: Platform.OS === 'android' ? filePath : filePath.replace('file://', ''),
|
|
uri: `file://${filePath}`,
|
|
type: 'text/plain',
|
|
name: fileName,
|
|
// blobValue: new Blob([fileContent], { type: 'text/plain' })
|
|
};
|
|
formData.append('file', fileToAppend as any);
|
|
|
|
const response = await fetch('http://192.168.1.114:8080/upload', {
|
|
method: 'POST',
|
|
// headers: {
|
|
// // 注意:不要手动设置 Content-Type,让浏览器自动设置
|
|
// 'Content-Type': 'multipart/form-data'
|
|
// },
|
|
body: formData,
|
|
});
|
|
// const response = await fetch('http://192.168.1.114:8080/api/standard-rail/list', {
|
|
// method: 'POST',
|
|
// });
|
|
|
|
if (response.ok) {
|
|
// const json = await response.json();
|
|
// console.log(json);
|
|
console.log('文件上传成功');
|
|
} else {
|
|
console.log('上传失败:' + response.status);
|
|
}
|
|
};
|
|
return (
|
|
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
|
|
<Button title="Write to File" onPress={writeToFile} />
|
|
<Button title="Read from File" onPress={readFromFile} />
|
|
<Button title="测试上传" onPress={uploadFile} />
|
|
</View>
|
|
);
|
|
};
|
|
|
|
export default FileReadWriteExample;
|