Strapi 上传插件 - 如何放置从 strapi 后端 js 代码生成的文件

Strapi Upload Plugin - How to place a file generated from strapi backend js code

我需要生成导出的 CSV 文件并将其放在媒体库中。

构建生成 de CSV 的代码是一项简单的任务,因此我将仅展示函数调用:

var csvContent = await strapi.api.product.services.product.export();

尝试将其放入媒体库时出现的问题。 到目前为止,我创建的唯一解决方案是使用 post 到 /upload 端点,但这不是专业的解决方案,所以我正在寻找替代方案。

我的代码:

var csvContent = await strapi.api.product.services.product.export(); //trus me, it works
const rootDir = process.cwd();
const fileName = 'ExportedProducts' + new Date().toDateString();
fs.writeFileSync(rootDir + '/public/uploads/' + fileName + '.csv', csvContent);
const form = new FormData();
form.append('files', 'textodeprueba', rootDir + '/public/uploads/' + fileName + '.csv');
axios.defaults.headers.common['Authorization'] = 'Bearer  SAMPLE_TOKEN';
axios.post(`http://localhost:1337/upload`, form, {
    headers: form.getHeaders(),
})
.then(res => {
    strapi.log.info("Building Products CSV File - Status: Finished - Date: " + new Date());
    result.status= "Finished";
})
.catch(err => {
    strapi.log.info("Building Products CSV File - Status: Failed - Date: " + new Date());
    result.status = "Failed";
    result.err = res;
});

此代码有效,但由于我是 node 和 strapi 的新手,所以有很多错误:

  1. 我将文件放在生成文件的文件夹中,然后 post 将其发送到 API。
  2. 我正在对令牌进行硬编码以授予对 API.
  3. 的访问权限

我找不到内部调用上传服务的方法。 有什么想法或文档可以阅读吗?

#######################################

21 年 3 月 8 日更新: 我尝试使用内部服务替换 post。 这是一个更好的主意,但内部服务不存在。

我将尝试创建 de collection 类型以检查它是否使用 'upload_file' table.

var csvContent = await strapi.api.product.services.product.export();
const rootDir = process.cwd();
const fileName = 'ExportedProducts' + new Date().toDateString() + '.csv';
fs.writeFileSync(rootDir + '/public/uploads/' + fileName, csvContent);
var stats = fs.statSync(rootDir + '/public/uploads/' + fileName);
strapi.query('upload_file').create({
  name: fileName,
  alternativeText: "",
  caption: "",
  hash: uuid.v4(),//random hash
  ext: ".csv",
  mime: "text/csv",
  size: stats.size,
  url: "/uploads/" + fileName,
  provider: "local",
  width: null,
  heught: null

});

错误信息:

Error: The model upload_file can't be found.

社区在 THIS POST 上提供了很多帮助。

上传插件允许我们上传新文件,并可选择将其重新分配到 collection。

首先以上传文件为例:

const mime = require('mime'); //will need to install with "npm i mime"
const fs = require('fs');
const rootDir = process.cwd();
const fileName = 'test.csv';
const filePath = `${rootDir}/public/uploads/${fileName}`
const stats = fs.statSync(filePath);

//uploading it directly to upload services.
await strapi.plugins.upload.services.upload.upload({
    data:{}, //mandatory declare the data(can be empty), otherwise it will give you an undefined error. This parameters will be used to relate the file with a collection.
    files: {
        path: filePath, 
        name: fileName,
        type: mime.getType(filePath), // mime type of the file
        size: stats.size,
    },
});

在下一轮中,将您上传的文件与 collection 行相关联的方式。

const fs = require('fs');
const mime = require('mime'); //used to detect file's mime type

const rootDir = process.cwd();
const fileName = 'ExportedProducts' + new Date().toDateString() + '.csv';
const filePath = rootDir + '/public/uploads/' + fileName;

var stats = fs.statSync(filePath);

await strapi.plugins.upload.services.upload.upload({
data: {
    refId: collectionLine.id,
    ref: 'collectionName',
    field: 'fieldName-mediaType',
}, 
files: {
    path: filePath, 
    name: fileName,
    type: mime.getType(filePath), // mime type of the file
    size: stats.size,
    },
});

请注意,社区成员建议使用“mime-types”库,但在尝试调用 getType 函数时会抛出错误。所以我用“mime”替换了它。

感谢阅读,希望对您有所帮助!