How to delete file from upload folder in strapi?

人盡茶涼 提交于 2021-01-28 06:11:10

问题


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?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/58551844/how-to-delete-file-from-upload-folder-in-strapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!