Search code examples
imagereact-nativerequire

React Native Retrieving Image file paths from Database


I am wondering how to model an application in React Native that retrieves images from a database and displays them to the user. I am planning to store images in a directory and have a database store the file paths for all of the images.

But, a problem that I found that other people encounter is that React Native requires a completely static file path in the source code. A solution that I frequently saw was one where a single index or switch statement is made to refer to all of the images. I believe that this model, however, would not work for my application as users should be able to upload their own images, which would then be stored on the server with its file path put into the database, but would not be represented in the switch statement. What kind of solution might there be for this situation?


Solution

  • For my react-native app, for uploading photos, I used react-native-image-picker to choose a picture from the user's device and rns3 to send the picture to aws s3. For the file name of the picture, I used the app name, plus the moment js library to dynamically create a unique file name. You can also use a uuid as well.

    For example :

      ImagePicker.showImagePicker(options, response => {
    
        if (response.didCancel) {
          // alert cancel
        } else if (response.error) {
          // alert error
        } else {
          const { uri } = response;
          const extensionIndex = uri.lastIndexOf(".");
          const extension = uri.slice(extensionIndex + 1);
    
          const file = {
            uri,
            name: `${YourAppName}_${moment.utc().format("YYYY-MM-DD-HH-mm-ss")}.${extension}`,
            type: "image/jpeg"
          };
    
          const options = {
            keyPrefix: ****,
            bucket: ****,
            region: ****,
            accessKey: ****,
            secretKey: ****
          };
    
          // send file to aws s3 and to your db ...
    
          RNS3.put(file, options)
            .progress(event => {
              console.log(`percent: ${event.percent}`);
            })
            .then(response => {
              if (response.status !== 201) {
                console.error(response.body);
                return;
              }
    
              // this will contain the image url
              let image = response.headers.Location;
    
              // send image url to your db
    
            })
        })
    

    For displaying the images, simply use the url stored in the db.