Search code examples
powershellamazon-web-servicessvgamazon-s3aws-powershell

Exclude files or certain type when writing to Amazon AWS S3


I am trying to upload folders to S3 to serve as static website. The problem I have is that within the folders, there are files of certain extensions such as .css, .png, .svg, etc. I am using AWS PowerShell tools and when I upload the following command, the .svg files are uploaded with wrong content-type.

Write-S3Object -BucketName bucket-name -Folder folderName -Recurse -Force -KeyPrefix folderName -CannedACLName NoACL

As a workaround, I came up with is to iterate the folders and do not upload the .svg files. The re-iterate the folders and only upload .svg setting up correct -content-type

Write-S3Object -BucketName bucket-name -Folder folderName -Recurse -Force -KeyPrefix folderName -CannedACLName NoACL -SearchPattern "*.svg" -ContentType "image/svg+xml"

So I have two questions here.

1) Instead of doing the two step approach, can I upload all the files in one go setting up correct content-type for svg files?

2) Is there a away to specify files to exclude in -SearchPattern parameter of Write-S3Object?

Thanks.


Solution

  • First thing is that I cannot use -ContentType "image/svg+xml" when uploading the folder since it doesn't apply the content-type to the files.

    So I took a two step approach; first uploading all files including SVG with incorrect Content-Type. This is to create the folders in case the folder only has SVG files.

    Write-S3Object -BucketName react-ui -Folder $i.FullName -Recurse -KeyPrefix $i.Name -CannedACLName NoACL
    

    After that, I re-upload the SVG file with correct Content-Type of /svg+xml". The -Key parameter is really important here since you can define the path of target folder using this.

    foreach ($i in Get-ChildItem $path -Recurse -Include "*.svg") 
    {
      $filename = [System.IO.Path]::GetFileName($i)
      $awsPath = $i.DirectoryName.Substring($i.DirectoryName.IndexOf($path) + $path.Length)
      $fileWithPath = $awsPath + "\"+ $filename
      Write-S3Object -BucketName react-ui -File $i -Key $fileWithPath -CannedACLName NoACL -ContentType "image/svg+xml"
    }