pingdotgg / uploadthing

File uploads for modern web devs
https://uploadthing.com
MIT License
3.97k stars 290 forks source link

feat: Ability to remove images that I know are being replaced #736

Open wondergod007 opened 5 months ago

wondergod007 commented 5 months ago

Describe the feature you'd like to request

If I am uploading an image to replace a previously uploaded image, I'd like to pass in the previous image URL so that this can be deleted since I know it will be replaced by the new image being uploaded. This would ensure my file store usage remains low.

Describe the solution you'd like to see

On uploading a new image, I'd like to set a property of the image URL to delete when this image is successfully uploaded.

Additional information

No response

๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Contributing

markflorkowski commented 5 months ago

We do have some plans to do things like this, for now though, you can pass that information to onUploadComplete() and call deleteFiles() there.

Something like this could work:

export const uploadRouter = {
  imageUploader: f({
    image: {
      maxFileSize: "4MB",
    },
  })
    .input(z.object({
      prevFile: z.string().optional(),
    }))
    .middleware(({ req, input }) => {
      // check for auth
      const user = auth(req);
      if (!user)  throw new Error("Unauthorized");

      // Return some metadata to be stored with the file
      return { userId: user.id, input };
    })
    .onUploadComplete(async ({ file, metadata: { prevFile }}) => {
      if(prevFile) await utapi.deleteFiles(prevFile);
    }),
} satisfies FileRouter;