Amazon Web Services S3 API Java Client : update file object key with correct content type

By default the uploaded file content type is :
application/x-www-form-urlencoded; charset=utf-8

To change this you can do something like this :

  1. static AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
  2. public void validateKeyContentType(String key) {
  3.         try {
  4.             ObjectMetadata metadata = generateCorrectContentTypeObjMetaFromKeyName(key);
  5.             
  6.             final CopyObjectRequest request = new CopyObjectRequest(bucket, key, bucket, key).withSourceBucketName(bucket)
  7.                 .withSourceKey(key)
  8.                 .withNewObjectMetadata(metadata).withCannedAccessControlList(CannedAccessControlList.PublicRead);
  9.             s3Client.copyObject(request);
  10.         } catch (Exception exception) {
  11.             LOG.info(exception.getMessage());
  12.         }
  13.     }
  14. public ObjectMetadata generateCorrectContentTypeObjMetaFromKeyName(String key){
  15.         ObjectMetadata metadata = new ObjectMetadata();
  16.         String contentType = getFileContentTypeFromFileName(key);
  17.         
  18.         LOG.log(Level.INFO, "Setting content type : " + contentType);
  19.         metadata.setContentType(contentType);
  20.         return metadata;
  21.     }
  22. /*
  23. These method takes some argument like "bucket1uploads/file100.mp4" and returns it's content type "video/mp4" by parsing the text (javax.activation)
  24. */
  25.     public static String getFileContentTypeFromFileName(String filePath) {
  26. //javax.activation is too old and misses these content types
  27.         MimetypesFileTypeMap ftmp = new MimetypesFileTypeMap();
  28.         ftmp.addMimeTypes("audio/mp3 mp3 MP3");
  29.         ftmp.addMimeTypes("video/mp4 mp4 MP4");
  30.         ftmp.addMimeTypes("video/mkv mkv MKV");
  31.         ftmp.addMimeTypes("video/webm webm WEBM");
  32.         ftmp.addMimeTypes("video/flv flv FLV");
  33.         ftmp.addMimeTypes("video/x-flv x-flv X-FLV");
  34.         return ftmp.getContentType(filePath);
  35.     }

No comments:

Post a Comment