I am using an angular SPA & spring boot backend. To upload a new file to S3 directly from the UI. Can the spring boot backend return a S3 signed URL to which the user directly uploads the file using the angular UI?
Assistant
Yes, your Spring Boot backend can generate and return an Amazon S3 pre-signed URL, which your Angular SPA can then use to upload files directly to the S3 bucket.
Here's an outline of the process:
In your Spring Boot application, integrate the AWS SDK for Java. Add the following dependency to your pom.xml:
code
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.xxx</version> <!-- use the latest version -->
</dependency>
Configure your AWS credentials in the Spring Boot application. You can set them in resources/application.properties or via environment variables. For example:
Use the method above to create a REST endpoint that returns a pre-signed URL:
java
@RestController
@RequestMapping("/presigned-url")
public class PresignedUrlController {
// ...generatePresignedUrl method
@GetMapping
public ResponseEntity<?> getPresignedUrl(@RequestParam("filename") String filename) {
String bucketName = "YOUR_BUCKET_NAME";
URL url = generatePresignedUrl(bucketName, filename);
if (url == null)
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(url, HttpStatus.OK);
}
}
In your Angular SPA, call this REST endpoint and then use the returned pre-signed URL to upload the file. You can use the axios library or the built-in HttpClient module: