Home > OS >  How to display a preview of file from local storage in a react native component?
How to display a preview of file from local storage in a react native component?

Time:01-10

I am working on a App in which there's an upload button through which user can select a file to be sent to the server. But before the file is send i would like to display a preview of the file below the upload button. How can that be implemented? I don't want to preview it separately.. It should be visible below the upload button inside a react native component.

CodePudding user response:

I assume, you are using this package 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'
      />

Even if you are not using this library. The way to show any image. You need to get its URI

Then,

In Image Component (React)

You can show it like this,

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

CodePudding user response:

For displaying an image is pretty simple, you can have a state to store the image or pdf details once you have uploaded it.

To display the image, <Image source={{uri: imageUrl}}/> // which you stored in state

To display a pdf, you can use react-native-view-pdf package,

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;

and call it as:

<ViewPdf 
     imageUrl = {uri} 
     imageName = {fileName} 
     styles = {styles.thumbnail_image}
 />
  •  Tags:  
  • Related