如何从 strapi 的上传文件夹中删除文件?

How to delete file from upload folder in strapi?

我有一个媒体类型的条目。

当我试图删除一些条目时,我使用代码:

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

已成功删除条目,以及 "Files Upload" 中的记录。但文件仍保留在 upload 文件夹中。我怎样才能删除它?

尝试调用 strapi 组织。控制器中的功能:

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);
}

假设您的内容类型是文章,请尝试以下操作:

在 /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 });
  }
}

此代码从媒体库中删除条目并从 uploads 目录中删除文件:

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

删除 Strapi V4 文件的代码为:

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

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

对于 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);

一定要先删除图片再删除相应的条目,比如要删除用户,先删除用户头像,再删除用户条目。否则,您在删除图像时收到错误代码 500