title: How to display image from AWS s3 using spring boot and react?
body: <p>How to display images from amazon s3 bucket in react?
  Images are not being displayed using amazon s3,spring boot 2.5.3,react.</p>
  <p>I have tested the end points in postman, it works.</p>
  <p>React: Using Axios to connect to backend and MyDropZone</p>
  <p>Using axios to make a post request, I can confirm that images are being saved in s3.
  <a href="https://i.stack.imgur.com/NQFN8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NQFN8.png" alt="Saved image" /></a></p>
  <p>This is the reponse after making a post request, for the first 2 user.</p>
  <pre><code>[
     {
        &quot;userId&quot;:&quot;565c6cbe-7833-482d-b0d4-2edcd7fc6163&quot;,
        &quot;userName&quot;:&quot;John&quot;,
        &quot;imageUrl&quot;:&quot;pexels-photo-3147528.jpeg&quot;
     },
     {
        &quot;userId&quot;:&quot;3c776990-38e8-4de4-b7c6-7875c0ebb20f&quot;,
        &quot;userName&quot;:&quot;Anthony&quot;,
        &quot;imageUrl&quot;:&quot;pexels-photo-3147528.jpeg&quot;
     },
     {
        &quot;userId&quot;:&quot;bcac9cf2-5508-4996-953e-b18afe866581&quot;,
        &quot;userName&quot;:&quot;Peter&quot;,
        &quot;imageUrl&quot;:null
     }
  ]
  </code></pre>
  <p>React:</p>
  <pre><code>import './App.css';
  import axios from 'axios';
  import { useState, useEffect,useCallback } from 'react';
  import {useDropzone} from 'react-dropzone'
  
  
  
  //
  const UserProfiles = () =&gt; {
  
    const [userProfiles,setUserProfiles]=useState([])
  
    const fetchUserProfiles=() =&gt; {
      axios.get('http://localhost:5000/api/v1/users').then((response) =&gt; {
        console.log(response.data)
        setUserProfiles(response.data)
      })
    }
  
    useEffect(() =&gt; {
      fetchUserProfiles();
    }, [])
  
    return userProfiles.map((profile,index) =&gt; {
      return (
        &lt;div key={index}&gt;
          &lt;MyDropZone userId={profile.userId}&gt;&lt;/MyDropZone&gt;
          &lt;h3&gt;{profile.userId}&lt;/h3&gt;
          {
            profile.userId ? (&lt;img src={`http://localhost:5000/api/v1/users/${profile.userId}/image/download`} /&gt; ) : &lt;h5&gt;No profile Image Uploaded&lt;/h5&gt;
          }
        &lt;/div&gt;
      );
    })
  }
  
  function MyDropZone({userId}) {
    const onDrop = useCallback(acceptedFiles =&gt; {
      // Do something with the files
      console.log(acceptedFiles[0])
      const file=acceptedFiles[0]
      //Form-data
      const formData = new FormData()
      formData.append('file', file)
      
      //Make a post req
      axios.post(`http://localhost:5000/api/v1/users/${userId}/image/upload`, formData, {
        headers: {
          'Content-Type':'multipart/form-data'
        }
      }).then((response) =&gt; {
        console.log(response)
        console.log(&quot;Uploaded&quot;)
      }).catch((error) =&gt; {
        console.log(error)
      })
    }, [])
    const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop})
  
    return (
      &lt;div {...getRootProps()}&gt;
        &lt;input {...getInputProps()} /&gt;
        {
          isDragActive ?
            &lt;p&gt;Drop the files here ...&lt;/p&gt; :
            &lt;p&gt;Drag 'n' drop some files here, or click to select files&lt;/p&gt;
        }
      &lt;/div&gt;
    )
  }
  
  
  
  function App() {
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;UserProfiles &gt;&lt;/UserProfiles&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>
  <p>The image is not being loaded in the UI.</p>
  <pre><code>{
   profile.userId ? (&lt;img src={`http://localhost:5000/api/v1/users/${profile.userId}/image/download`} /&gt; ) : &lt;h5&gt;No profile Image Uploaded&lt;/h5&gt;
  }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/KgICg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KgICg.png" alt="This is how it looks in the inspect element." /></a></p>
  <p>When I go to this <code>http://localhost:5000/api/v1/users/565c6cbe-7833-482d-b0d4-2edcd7fc6163/image/download</code> URL via browser.
  It has a response with</p>
  <pre><code> ÿØÿàJFIFHHÿâICC_PROFILElcmsmntrRGB XYZ Ü)9acspAPPLöÖÓ-lcms descü^cprt\wtpthbkpt|rXYZgXYZ¤bXYZ¸rTRCÌ@gTRCÌ@b
  </code></pre>
  <p><strong>Update Added Backend code.</strong></p>
  <p>controller</p>
  <pre><code>@GetMapping(path = &quot;{userId}/image/download&quot;)
  public byte[] downloadUserProfileImage(@PathVariable(&quot;userId&quot;) UUID userId) {
      return userProfileService.downloadUserProfileImage(userId);
  }
  </code></pre>
  <p>Service:</p>
  <pre><code>private UserProfile getUserProfileOrThrow(UUID userId) {
      UserProfile userProfile = userProfileRepository.getUserProfiles()
              .stream()
              .filter(profile -&gt; profile.getUserId().equals(userId)).findFirst().orElseThrow(() -&gt; new IllegalStateException(&quot;User does not exist&quot; + userId)
              );
      return userProfile;
  }
  public byte[] downloadUserProfileImage(UUID userId) {
      UserProfile userProfile=getUserProfileOrThrow(userId);
      String path = String.format(&quot;%s/%s&quot;,
              BucketName.PROFILE_IMAGE.getBucketName(),
              userProfile.getUserId());
  
      return userProfile.getImageUrl()
              .map(key -&gt; fileStore.download(path, key))
              .orElse(new byte[0]);
  }
  </code></pre>
  <p>FileStore:</p>
  <pre><code>@Service
  public class FileStore {
      private final AmazonS3 s3;
  
  @Autowired
  public FileStore(AmazonS3 s3) {
      this.s3 = s3;
  }
  public void save(String path,
                   String fileName,
                   Optional&lt;Map&lt;String, String&gt;&gt; optionalMetadata,
                   InputStream inputStream) {
      ObjectMetadata metadata = new ObjectMetadata();
  
      optionalMetadata.ifPresent(map -&gt; {
          if (!map.isEmpty()) {
              map.forEach(metadata::addUserMetadata);
          }
      });
  
      try {
          s3.putObject(path, fileName, inputStream, metadata);
      } catch (AmazonServiceException e) {
          throw new IllegalStateException(&quot;Failed to store file to s3&quot;, e);
      }
  }
  
  public byte[] download(String path, String key) {
      try {
          S3Object object = s3.getObject(path, key);
          return IOUtils.toByteArray(object.getObjectContent());
      } catch (AmazonServiceException | IOException e) {
          throw new IllegalStateException(&quot;Failed to download file to s3&quot;, e);
      }
  }
  }
  </code></pre>
  <p>Amazon s3 config:
  @Configuration
  public class AmazonConfig {</p>
  <pre><code>@Bean
  public AmazonS3 s3(){
      AWSCredentials  awsCredentials=new BasicAWSCredentials(&quot;my-credentials&quot;,&quot;my-secret-key&quot;);
  
      return AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
              .withRegion(Regions.AP_SOUTH_1)
              .build();
  }
  </code></pre>
  <p>}</p>
  <p>UserProfile:</p>
  <pre><code>public class UserProfile {
      private final UUID userId;
      private final String userName;
      private String imageUrl;
  
      //This might be null
      public Optional&lt;String&gt; getImageUrl() {
          return Optional.ofNullable(imageUrl);
      }
  
      public void setImageUrl(String imageUrl) {
          this.imageUrl = imageUrl;
      }
  //getters &amp; setters
      }
  </code></pre>