Skip to content
Advertisement

Assigning name to a org.springframework.core.io.Resource object

I am looking for a way to assign/set a filename to a org.springframework.core.io.Resource object. The object does not have a function available to do this. The getFileName method in my case returns a null.

I do not want to create a multipartfile from the Resource object since my Open API spec does not accept it.

Advertisement

Answer

I achieved it like this

//Retrieved the object from S3
S3Object s3Object = amazonS3client.getObject(s3Config.getBucket(), key);
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
String fileName = s3Object.getObjectMetadata().getUserMetaDataOf("fileName");

//create a ByteArrayResource from the input stream and assigned the fileName
ByteArrayResource fileAsResource = new ByteArrayResource(IOUtils.toByteArray(objectInputStream)) {
                    @Override
                    public String getFilename() {
                        return fileName;
                    }

                    @Override
                    public long contentLength() {
                        return s3Object.getObjectMetadata().getContentLength();
                    }
                };
Advertisement