【问题标题】:How to display a preview of file from local storage in a react native component?如何在反应原生组件中显示来自本地存储的文件预览?
【发布时间】:2022-01-08 14:49:45
【问题描述】:

我正在开发一个应用程序,其中有一个上传按钮,用户可以通过该按钮选择要发送到服务器的文件。但在发送文件之前,我想在上传按钮下方显示文件的预览。那如何实施?我不想单独预览它。它应该在 React Native 组件内的上传按钮下方可见。

【问题讨论】:

  • 您要显示什么类型的文件?
  • 任何类型的文档.. Pdf、txt、表格等

标签: javascript android reactjs react-native


【解决方案1】:

我假设,您正在使用这个包 react-native-image-picker

const handleCaptureImage = () => {
    ImagePicker.showImagePicker({
      title: 'Take picture',
      chooseFromLibraryButtonTitle: 'Choose picture from gallery',
  
    }, response => {
      if (response.didCancel) {
          
      } else if (response.error) {
          console.log(response.error)
      } else {
          let source = { uri: response.uri };
          let data = {
              source: source,
              response: response,
              taken:true,
              mode:0 // For Image Capture
          };
          setimageURI(data);
      }
  });
   }

<Image
        source={imageURI.source}
        style={_._dpcontainer}
        resizeMode='contain'
      />

即使你没有使用这个库。显示任何图像的方式。你需要获取它的URI

那么,

在图像组件中(React)

你可以这样显示,

<Image source={{uri: YOUR IMAGE URI}}/>

【讨论】:

  • 有没有办法在应用程序中打开 pdf 或文本文件?在新屏幕或组件上?
【解决方案2】:

因为显示图像非常简单,上传后您可以有一个状态来存储图像或 pdf 详细信息。

要显示图像, &lt;Image source={{uri: imageUrl}}/&gt; // 你存储的状态

要显示pdf,可以使用react-native-view-pdf包,

ViewPdf.tsx

import React from 'react';
import {View} from 'react-native';
import Pdf from 'react-native-view-pdf';

export type Props = {
    imageUrl: string,
    imageName: string,
    styles: object
}

const ViewPdf: React.FC<Props> = ({
    imageUrl,
    imageName,
    styles
}) => {
    const source = { uri: imageUrl, cache: true };
    return(
        <View style = {{flex: 1}}>
            <Pdf resource={imageUrl} style={styles} fadeInDuration={100}/>
        </View>
    )
};

export default ViewPdf;

并将其称为:

<ViewPdf 
     imageUrl = {uri} 
     imageName = {fileName} 
     styles = {styles.thumbnail_image}
 />

【讨论】:

  • 其他文件呢?
  • 那么你可以使用 react-native-file-viewer。您可以查看任何类型的文件。您可以使用与上述相同的结构。
  • 好的,感谢您的快速回复。还有一件事,有没有一种方法可以在不下载远程 URL 的情况下查看文件?
  • 网页视图可能在那里有用。
  • 是的,我只使用过 webView...但它有时会加载 pdf,有时只是一个空白屏幕。
猜你喜欢
  • 2021-03-15
  • 2013-10-30
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2018-02-18
  • 2018-07-21
  • 2020-10-10
相关资源
最近更新 更多