Strapi 的 Upload 套件預設會安裝 Local 版本。若你要搭配第三方上傳套件(像是 AWS–S3)的話,那會需要在 Strapi 中作一些設定。這邊筆記下過程中遇到的各種狀況和解決方法。
內容
1. 檔名為 plugins.js 或是 plugins.ts
在 config 資料夾內新增 plugin 檔案時,請特別注意檔名是 plugin 複數。在檔名錯誤下,執行上會呈現「一直使用原有 local 端」上傳機制的結果,並不會報錯,會導致你排查到懷疑人生。
2. middlewares.js 中的 strapi::security 需要新增上 s3 的 bucket domain
由於瀏覽器的安全性要求,若你沒有加上 domain 的話,會導致圖片無法呈現。( 你可以透過瀏覽器的 DevTools 得知你結果有沒有設定正確 )
3. S3 的 CORS 所需要開啟的建議設定:
1 2 3 4 5 6 7 8 9 |
[ { <span class="pl-ent">"AllowedHeaders"</span>: [<span class="pl-s"><span class="pl-pds">"</span>*<span class="pl-pds">"</span></span>], <span class="pl-ent">"AllowedMethods"</span>: [<span class="pl-s"><span class="pl-pds">"</span>GET<span class="pl-pds">"</span></span>], <span class="pl-ent">"AllowedOrigins"</span>: [<span class="pl-s"><span class="pl-pds">"</span>YOUR STRAPI URL<span class="pl-pds">"</span></span>], <span class="pl-ent">"ExposeHeaders"</span>: [], <span class="pl-ent">"MaxAgeSeconds"</span>: <span class="pl-c1">3000</span> } ] |
4. S3 的最小執行權限
1 2 3 4 5 6 7 |
<span class="pl-ent">"Action"</span>: [ <span class="pl-s"><span class="pl-pds">"</span>s3:PutObject<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>s3:GetObject<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>s3:ListBucket<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>s3:DeleteObject<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>s3:PutObjectAcl<span class="pl-pds">"</span></span> ] |
程式碼
參考資料
1. @strapi/provider-upload-aws-s3
2. AWS S3 Provider – Not Working