Martin Larizzate
Martin Larizzate

Reputation: 910

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

I need to generate an export CSV file and place it on the Media Library.

Building the code to generate de CSV was an easy task so I will show only the function call:

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

Ths issue strated when trying to place it on the media library. Until now, the only solution I founded was to use a post to /upload endpoint but as this is not a professional solution so I'm looking for alternatives.

My code:

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

This code works but as I'm new with node and strapi, there are many mistakes:

  1. I'm placing the file in the folder to generate the file and then y post it to the API.
  2. I'm hardcoding a token in orden to grant access to the API.

I can't find a way to call the upload service internaly. any ideas or documentation to read about it?

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

UPDATE 08-Mar-21: I tried to replace the post using internal service. It's a better idea but the internal service does not exists.

I'll try to create de colection type in order to check if it uses the '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 Message:

Error: The model upload_file can't be found.

Upvotes: 3

Views: 5472

Answers (1)

Martin Larizzate
Martin Larizzate

Reputation: 910

The community helped a lot on THIS POST .

Upload plugin allow us to upload a new file with the option to realet it to a collection.

First the example to just upload the file:

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

And in the next round, the way to relate your uploaded file with a collection line.

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

Note that a community member suggested "mime-types" library, but it throws an error when try to call getType function. So I replaced It with "mime".

Thanks for reading and hope to help!

Upvotes: 5

Related Questions