How to delete file from upload folder in strapi?

Viewed 4107

I have an entry with field of type media.

When I'm trying to delete some entry, I'm using code:

strapi.query('entry').delete({ id: entry.id });
strapi.query('file', 'upload').delete({ id: entry.image.id });

The entry is deleted successfully, as well as record from "Files Upload". But file still stays in upload folder. How can I delete it?

5 Answers

This code removes entry from Media Library and deletes files from uploads directory:

const file = await strapi.plugins['upload'].services.upload.fetch({ id });
await strapi.plugins['upload'].services.upload.remove(file);

Try to invoke the strapi org. functions in your controller:

delete: async ctx => {
    ctx.body = await strapi.plugins['content-manager'].services['contentmanager'].delete(ctx.params, ctx.request.query);
},

deleteAll: async ctx => {
    ctx.body = await strapi.plugins['content-manager'].services['contentmanager'].deleteMany(ctx.params, ctx.request.query);
}

Try the following, assuming your content type was article:

in /api/articles/controllers/articles.js

 'use strict';
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');

module.exports = {
  async delete(ctx) {
    const { id } = ctx.params;
    const entity = await strapi.services.articles.delete({ id });

    //with strapi multiple media
    if(entity){
      if (entity.gallery.length > 0) {
        entity.gallery.forEach(image => {
          strapi.plugins.upload.services.upload.remove(image);
        });
      }
    }

    //or with strapi single media
    if(entity){
      strapi.plugins.upload.services.upload.remove(entity.image);
    }

    return sanitizeEntity(entity, { model: strapi.models.articles });
  }
}

The code to remove a file for Strapi V4 would be:

const file = await strapi.plugins['upload'].services.upload.findOne(id);
await strapi.plugins['upload'].services.upload.remove(file);

or

const file = await strapi.plugins['upload'].services.upload.findMany({
 where: { id } 
});
await strapi.plugins['upload'].services.upload.remove(file[0]);

For Strapi v4.0.7:

// This will delete the image entry from Strapi.
const imageEntry = await strapi.db.query('plugin::upload.file').delete({
    where: { id: imageID },
});
// This will delete corresponding image files under the *upload* folder.
strapi.plugins.upload.services.upload.remove(imageEntry);

Make sure you delete images before deleting corresponding entries, for example, if you want to delete a user, delete the user's avatar first, then the user entry. Otherwise, you got an error code 500 when deleting images.

Related