#How to set upload `staticDir` value conditionally

1 messages · Page 1 of 1 (latest)

maiden perch
#

How can I change the upload.staticDir dynamically based on certain conditions, like the media_type? For example, I need to change the staticDir path based on whether the media is a profile_picture, project_image, or icon. How can I achieve this in PayloadCMS 3?

import type { CollectionConfig } from "payload";

export const Media: CollectionConfig = {
  slug: "media",
  access: {
    read: () => true,
  },
  fields: [
    {
      name: "media_type",
      type: "select",
      required: true,
      options: [
        { label: "Profile Picture", value: "profile_picture" },
        { label: "Project Image", value: "project_image" },
        { label: "Icon", value: "icon" },
      ],
    },
  ],
  upload: {
    staticDir: "", // Need to set this conditionally
    mimeTypes: ["image/*"],
  },
};

How can I set the staticDir to different directories based on the selected media_type (e.g., profile-pictures/, project-images/, or icons/)?

haughty thornBOT
dense meteor
#

hello @maiden perch
from what I see you want to organize your media into different directories, there's a feature currently under development by payload team
https://x.com/jarrodmflesch/status/1841195562915270872

the issue with staticDir that it's used to display images in collection list if it's changed things will break

for the moment either you can create another collection for icons this way it'll be stored in /media/icons/

or add a pre_fix to image names

pfp_myimage.png
icon_myicon.png

https://payloadcms.com/docs/upload/overview#custom-filename-via-hooks

maiden perch
bold yarrow
#

I was about to ask similar question for payload v2.

  • I need to store file in different directory to ensure the filename doesn't conflict, otherwise if another user uploads same named file like example.png, then it becomes example2.png so I need to have it per user like /user_id_here/example.png (actually, per project, anyway some folder name as field in the document)

I found the following but seems not helping me achieve this and I think it doesn't work:

My final idea:

  • to store desired file names at other field and at display/download of file to ensure the correct filename is used aka other field
#

I was thinking that I would pass prefix in beforeChange hook and it would appear in generateFileURL but prefix there always undefined and in generateFileURL you do not have access to the document

maiden perch
bold yarrow
#

But I can't figure out my use case 🥲 to have dynamically created directory in s3, fml

dense meteor
#

I have tested creating prefix and it work with s3 storage

    beforeOperation: [
      ({ req, operation }) => {
        if ((operation === 'create' || operation === 'update') && req.file) {
        
          req.file.name = req.data!.media_type + '_' + req.file.name
        }
      },
    ],

maiden perch
bold yarrow