Prozorov
Prozorov

Reputation: 159

Image upload/download using aws lambda

I am trying to create a lambda function which accepts an image as multipart object, then does some processing and uploads it to s3 bucket and provides some response back to the user.

I have found some examples how to proceed however, i do not understand do i have to create two lambda functions and upload separate jars or it can be done differently.

So far i have service that parses multipart and uploads to s3 , my question is how to approach using aws lambdas, thank you guys

public String uploadFile(MultipartFile multipartFile) {
        String fileUrl = "";
        try {
            File file = convertMultiPartToFile(multipartFile);
            String fileName = generateFileName(multipartFile);
            fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
            uploadFileTos3bucket(fileName, file);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
        return fileUrl;
    }

    private File convertMultiPartToFile(MultipartFile file){
        File convFile = new File(file.getOriginalFilename());
        try {
            FileOutputStream fos = new FileOutputStream(convFile);
            fos.write(file.getBytes());
            fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    }

Upvotes: 0

Views: 1111

Answers (1)

Kulasangar
Kulasangar

Reputation: 9454

I'd suggest you can simply use one lambda function, which should be integrated with an api gateway endpoint. So the user can invoke the endpoint (post) with the file that needs to be uploaded into S3 and then from the lambda function you can do the rest ( processing + uploading to s3) and then return some response back to the user.

This could be a starting point.

to get the s3 URL of your uploaded file:

s3Client.getUrl("your_bucket_name", "your_file_key").toExternalForm();

Here is another example to resize the images in S3 using Lambda. It's JS code though and uses only one Lambda function.

Upvotes: 2

Related Questions