廓形仪rn版本-技术调研
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

  1. import React, { useEffect } from 'react';
  2. import { View, Text, Button } from 'react-native';
  3. import RNFS from 'react-native-fs';
  4. import { Platform } from 'react-native';
  5. const FileReadWriteExample = () => {
  6. // 定义文件路径
  7. const filePath = RNFS.DocumentDirectoryPath + '/example.txt';
  8. // 写入文件的函数
  9. const writeToFile = async () => {
  10. try {
  11. const content = 'Hello, this is a test file content.';
  12. // 使用 RNFS.writeFile 方法写入文件
  13. await RNFS.writeFile(filePath, content, 'utf8');
  14. console.log('File written successfully');
  15. } catch (error) {
  16. console.error('Error writing file:', error);
  17. }
  18. };
  19. // 读取文件的函数
  20. const readFromFile = async () => {
  21. try {
  22. // 使用 RNFS.readFile 方法读取文件
  23. const contents = await RNFS.readFile(filePath, 'utf8');
  24. console.log('File content:', contents);
  25. } catch (error) {
  26. console.error('Error reading file:', error);
  27. }
  28. };
  29. useEffect(() => {
  30. // 在组件挂载时创建文件目录
  31. RNFS.mkdir(RNFS.DocumentDirectoryPath)
  32. .then(() => {
  33. console.log('Directory created successfully');
  34. })
  35. .catch(error => {
  36. console.error('Error creating directory:', error);
  37. });
  38. }, []);
  39. const uploadFile = async () => {
  40. const formData = new FormData();
  41. const fileName = filePath.split('/').pop();
  42. const fileContent = await RNFS.readFile(filePath, 'utf8');
  43. const fileToAppend = {
  44. // uri: Platform.OS === 'android' ? filePath : filePath.replace('file://', ''),
  45. uri: `file://${filePath}`,
  46. type: 'text/plain',
  47. name: fileName,
  48. // blobValue: new Blob([fileContent], { type: 'text/plain' })
  49. };
  50. formData.append('file', fileToAppend as any);
  51. const response = await fetch('http://192.168.1.114:8080/upload', {
  52. method: 'POST',
  53. // headers: {
  54. // // 注意:不要手动设置 Content-Type,让浏览器自动设置
  55. // 'Content-Type': 'multipart/form-data'
  56. // },
  57. body: formData,
  58. });
  59. // const response = await fetch('http://192.168.1.114:8080/api/standard-rail/list', {
  60. // method: 'POST',
  61. // });
  62. if (response.ok) {
  63. // const json = await response.json();
  64. // console.log(json);
  65. console.log('文件上传成功');
  66. } else {
  67. console.log('上传失败:' + response.status);
  68. }
  69. };
  70. return (
  71. <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
  72. <Button title="Write to File" onPress={writeToFile} />
  73. <Button title="Read from File" onPress={readFromFile} />
  74. <Button title="测试上传" onPress={uploadFile} />
  75. </View>
  76. );
  77. };
  78. export default FileReadWriteExample;