How to upload images from local disk and create relation on json import?

Refactored a little bit your upload function.

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

module.exports = async (imgPath) => {
  // name of the file like image01.jpg
  const name = path.basename(imgPath);
  // read contents of file
  const buffer = await fs.statSync(imgPath);
  return strapi.plugins.upload.services.upload.upload({
    data: {}, //mandatory declare the data(can be empty), otherwise it will give you an undefined error.
    files: {
		path: imgPath, 
		name: name,
		type: mime.lookup(imgPath), 
		size: buffer.size,
	},
   });
};

1 Like