Skip to content

Instantly share code, notes, and snippets.

@hami9x
Created August 30, 2017 10:55
Show Gist options
  • Save hami9x/2be4e05b82d3f0f5a9bb668f75935955 to your computer and use it in GitHub Desktop.
Save hami9x/2be4e05b82d3f0f5a9bb668f75935955 to your computer and use it in GitHub Desktop.
api/upload/services/upload.js
"use strict";
/**
* Module dependencies
*/
// Node.js core.
const path = require("path");
const fs = require("fs");
// Public node modules.
const _ = require("lodash");
module.exports = {
/**
* Upload files.
*
* @param part File extracted from the request body.
* @param ctx
* @returns {*}
*/
upload: function*(part, ctx) {
return new Promise(async function(resolve, reject) {
// Init and format variables.
const promises = [];
const defaultUploadFolder = "public/upload";
let stream;
ctx = ctx || {};
// Set the filename.
const filename =
Date.now().toString() +
"-" +
(_.kebabCase(part.filename) ||
Math.floor(Math.random() * 1000000).toString());
// Start uploading.
stream = fs.createWriteStream(
path.join(
process.cwd(),
strapi.api.upload.config.folder || defaultUploadFolder,
filename
)
);
part.pipe(stream);
// Register the data of the file in the database.
promises.push(
strapi.orm.collections.upload.create(
_.merge(part, {
createdBy: ctx.user && ctx.user.id,
originalFilenameFormatted: _.kebabCase(part.filename),
originalFilename: part.filename || "",
filename: filename
})
)
);
try {
const uploadDescriptions = await promises;
resolve(uploadDescriptions);
} catch (err) {
strapi.log.error(err);
reject(err);
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment