Rename File On Upload? Not Overwriting Other Uploads #1153
-
To prevent uploads from overwriting each other in our media folder, is there a way to generate a unique name for a file upon upload?
Would this be accomplished by means of a middleware or something I'm missing? Aka: Thank you for responses / feedback! |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
Uploaded files having the same name as something already in storage will be renamed with a If you prefer to have a unique hash instead, you'd need to do a bit of work which I can go into some detail if you want. Let me know what you think! |
Beta Was this translation helpful? Give feedback.
-
Adding to this, it looks like a beforeOperation: [async ({ args }) => {
const files = args.req?.files;
if (files && files.file && files.file.name) {
const parts = files.file.name.split('.');
files.file.name = `${(Math.random() + 1).toString(36).substring(2)}.${parts[parts.length - 1]}`;
}
}] It just replaces the filename in the request before anything is saved. Note that this does not at all guarantee that the filename is unique, although depending on usage collision are probably rare anyway and in case they do happen we can rely on the built-in functionality of adding the Using |
Beta Was this translation helpful? Give feedback.
-
I found this thread because I want to sanitize filenames to not include spaces. something like Solved it like this if anyone cares: import { CollectionBeforeOperationHook } from 'payload/types'
/**
* Sanitizes the filename for upload collections to not include spaces or special characters
*/
export const sanitizeFileName: CollectionBeforeOperationHook = async ({
args,
}) => {
const files = args.req?.files
if (
files !== undefined &&
files !== null &&
typeof files === 'object' &&
files.file !== undefined &&
files.file !== null &&
typeof files.file === 'object' &&
files.file.name !== undefined &&
files.file.name !== null &&
typeof files.file.name === 'string'
) {
files.file.name = files.file.name.replace(/[^a-z0-9.]/gi, '_').toLowerCase()
}
} |
Beta Was this translation helpful? Give feedback.
-
IMO the options passed to |
Beta Was this translation helpful? Give feedback.
-
Anything from suggestions works for me, so I needed to debug it and this works for me. import { CollectionConfig } from 'payload'
export const Media: CollectionConfig = {
slug: 'media',
upload: true,
fields: [
{
name: 'text',
type: 'text',
},
],
hooks: {
beforeOperation: [
async (req) => {
if (req.operation === 'create') {
if (req.req.file)
req.req.file.name = req.req.file?.name.replace(/[^a-z0-9.]/gi, '').toLowerCase()
}
},
],
},
} |
Beta Was this translation helpful? Give feedback.
I found this thread because I want to sanitize filenames to not include spaces.
Since uploads always have a URL attached, should this maybe be a core functionality?
something like
sanitizeFilename: true
?Solved it like this if anyone cares: