当前位置:   article > 正文

react-native-document-picker一个适合react native打开本地文件,上传文件的组件;也可直接用react-native-fetch-blob

react-native-document-picker

一些配置介绍

  1. import DocumentPicker from 'react-native-document-picker';
  2. const FileTypes = {
  3. All: DocumentPicker.types.allFiles,// All document types, on Android this is */*, on iOS is public.content (note that some binary and archive types do not inherit from public.content)
  4. Image: DocumentPicker.types.images, // All image types (image/* or public.image)
  5. Text: DocumentPicker.types.plainText, // Plain text files ie: .txt (text/plain or public.plain-text)
  6. Audio: DocumentPicker.types.audio, // All audio types (audio/* or public.audio)
  7. PDF: DocumentPicker.types.pdf, // PDF documents (application/pdf or com.adobe.pdf)
  8. Zip: DocumentPicker.types.zip, // Zip files (application/zip or public.zip-archive)
  9. Csv: DocumentPicker.types.csv, //Csv files (text/csv or public.comma-separated-values-text)
  10. };
  11. let Manager = {
  12. // Pick a single file
  13. pickerSingleFile: (fileType, callback, errorCallback) => {
  14. try {
  15. DocumentPicker.pick({
  16. type: [FileTypes[fileType]],
  17. }).then(res => {
  18. console.log(
  19. res.uri,
  20. res.type, // mime type
  21. res.name,
  22. res.size
  23. );
  24. if (callback) {
  25. callback(res);
  26. }
  27. }).catch(error => {
  28. console.log(error);
  29. if (errorCallback) {
  30. errorCallback(error);
  31. }
  32. });
  33. } catch (err) {
  34. if (errorCallback) {
  35. errorCallback(err);
  36. }
  37. if (DocumentPicker.isCancel(err)) {
  38. // User cancelled the picker, exit any dialogs or menus and move on
  39. } else {
  40. throw err;
  41. }
  42. }
  43. },
  44. PickMultipleFiles: (fileType, callback, errorCallback) => {
  45. // Pick multiple files
  46. try {
  47. DocumentPicker.pickMultiple({
  48. type: [FileTypes[fileType]],
  49. }).then(results => {
  50. for (const res of results) {
  51. console.log(
  52. res.uri,
  53. res.type, // mime type
  54. res.name,
  55. res.size
  56. );
  57. }
  58. if (callback) {
  59. callback(results);
  60. }
  61. });
  62. } catch (err) {
  63. if (errorCallback) {
  64. errorCallback(err);
  65. }
  66. if (DocumentPicker.isCancel(err)) {
  67. // User cancelled the picker, exit any dialogs or menus and move on
  68. } else {
  69. throw err;
  70. }
  71. }
  72. },
  73. };
  74. module.exports = Manager;

实际使用,代码如下图所示

还需要借助另外一个组件:react-native-fetch-blob

  1. pickFile = async () => {
  2. try {
  3. const res = await DocumentPicker.pick({
  4. type: [DocumentPicker.types.allFiles],
  5. });
  6. console.log(res.uri);
  7. //output: content://com.android.providers.media.documents/document/image%3A4055
  8. RNFetchBlob.fs
  9. .stat(res.uri)
  10. .then((stats) => {
  11. console.log(stats.path);
  12. //output: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200831-WA0019.jpg
  13. })
  14. .catch((err) => {
  15. console.log(err);
  16. });
  17. } catch (err) {
  18. if (DocumentPicker.isCancel(err)) {
  19. } else {
  20. throw err;
  21. }
  22. }};

代码二:直接用react-native-fetch-blob

  1. 引入
  2. import RNFileSelector from "react-native-file-selector";
  3. const RNFS = require('react-native-fs');
  4. 函数
  5. // 上传附件
  6. onSwitchToFile = () => {
  7. RNFileSelector.Show(
  8. {
  9. title: '请选择文件',
  10. onDone: (path) => {
  11. RNFS.read('file://' + path , 20971520 , 0 , 'base64')
  12. .then(res => {
  13. const size = res.length - (res.length / 8) * 2
  14. console.log('文件大小为: ' + (size / 1024 / 1024).toFixed(2) + 'M' )
  15. if (size > 10485760) {
  16. toast("文件大小不能超过10M!")
  17. return false
  18. }
  19. let url = global.HOST + "media/upload"
  20. let formData = new FormData()
  21. let file = {
  22. uri: 'file://' + path,
  23. type: 'multipart/form-data',
  24. name: path || 'file',
  25. }
  26. formData.append("file", file)
  27. Net.upload(url, formData, res => {
  28. if (res.result === 0) {
  29. let fileName = path.substr(path.lastIndexOf("/") + 1)
  30. this.setState({
  31. fileName,
  32. fileUrl: res.ret
  33. })
  34. }
  35. })
  36. })
  37. .catch(error => {
  38. toast('文件上传失败!请重试!')
  39. console.log(error)
  40. })
  41. },
  42. onCancel: () => {
  43. console.log('cancelled')
  44. }
  45. }
  46. )
  47. }
  48. 页面中:
  49. <SafeAreaView style={{ backgroundColor: '#F2F2F2' }}>
  50. <ScrollView contentContainerStyle={{ padding: 10, backgroundColor: '#FFF', marginTop: 10 }}>
  51. <View style={[Styles.itemTitleContainer, { borderBottomWidth: 0 }]}>
  52. <View style={Styles.item_title}>
  53. <Text style={Styles.itemText}>上传附件</Text>
  54. </View>
  55. <View>
  56. <TouchableOpacity
  57. style={{
  58. borderColor: '#DDD',
  59. borderWidth: .5,
  60. paddingLeft: 15,
  61. paddingRight: 15,
  62. paddingTop: 8,
  63. paddingBottom: 8,
  64. flexDirection:"row",
  65. alignItems: 'center',
  66. justifyContent: 'center'
  67. }}
  68. onPress={() => this.onSwitchToFile()}
  69. >
  70. <Text>
  71. {
  72. this.state.fileName
  73. ? this.state.fileName
  74. : <Ionicons style={{ color: "#DDD" }} name="md-add" size={25} />
  75. }
  76. </Text>
  77. </TouchableOpacity>
  78. {
  79. this.state.fileName &&
  80. <View
  81. style={{
  82. position: 'absolute',
  83. top: -5,
  84. right: -5
  85. }}
  86. >
  87. <Text
  88. onPress={() => {
  89. this.setState({
  90. fileName: null,
  91. fileUrl: null
  92. })
  93. }}
  94. style={{
  95. width: 12,
  96. height: 12,
  97. borderRadius: 6,
  98. backgroundColor: '#ddd',
  99. fontSize: 10,
  100. textAlign: 'center',
  101. lineHeight: 12,
  102. color: '#fff'
  103. }}
  104. >
  105. x
  106. </Text>
  107. </View>
  108. }
  109. </View>
  110. </View>
  111. </ScrollView>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/938448
推荐阅读
相关标签
  

闽ICP备14008679号