mirror of
https://github.com/strapi/strapi.git
synced 2026-01-05 19:52:15 +00:00
Create route to upload on local server
This commit is contained in:
parent
4d1f973093
commit
848db478e3
@ -1,7 +1,7 @@
|
||||
{
|
||||
"routes": [
|
||||
{
|
||||
"method": "GET",
|
||||
"method": "POST",
|
||||
"path": "/",
|
||||
"handler": "Upload.index",
|
||||
"config": {
|
||||
|
||||
@ -15,11 +15,17 @@ module.exports = {
|
||||
*/
|
||||
|
||||
index: async (ctx) => {
|
||||
// Add your own logic here.
|
||||
const Service = strapi.plugins['upload'].services.upload;
|
||||
|
||||
const files = await Service.getFiles(ctx.request.body.files);
|
||||
|
||||
await Service.upload(files);
|
||||
|
||||
// Send 200 `ok`
|
||||
ctx.send({
|
||||
message: 'ok'
|
||||
});
|
||||
ctx.send(files.map((file) => {
|
||||
return {
|
||||
url: `/${file.key}`
|
||||
};
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
@ -22,7 +22,10 @@
|
||||
"test": "npm run lint",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"dependencies": {},
|
||||
"dependencies": {
|
||||
"stream-to-array": "^2.3.0",
|
||||
"uuid": "^3.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"strapi-helper-plugin": "3.0.0-alpha.10.1"
|
||||
},
|
||||
@ -43,4 +46,4 @@
|
||||
"npm": ">= 3.0.0"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,49 @@
|
||||
* @description: A set of functions similar to controller's actions to avoid code duplication.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
const _ = require('lodash');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const toArray = require('stream-to-array');
|
||||
const uuid = require('uuid/v4');
|
||||
|
||||
module.exports = {
|
||||
getFiles: async values => {
|
||||
if (_.size(values.files) === 0) {
|
||||
throw 'Missing files.';
|
||||
}
|
||||
|
||||
const files = _.isArray(values.files) ? values.files : [values.files];
|
||||
|
||||
return Promise.all(
|
||||
files.map(async stream => {
|
||||
const parts = await toArray(fs.createReadStream(stream.path));
|
||||
const buffers = parts.map(
|
||||
part => _.isBuffer(part) ? part : Buffer.from(part)
|
||||
);
|
||||
|
||||
return {
|
||||
key: `uploads/${uuid().replace(/-/g, '')}.${_.last(stream.name.split('.'))}`,
|
||||
buffer: Buffer.concat(buffers),
|
||||
mime: stream.type
|
||||
};
|
||||
})
|
||||
);
|
||||
},
|
||||
|
||||
upload: (files) => {
|
||||
return Promise.all(
|
||||
files.map(async file => {
|
||||
await new Promise((resolve, reject) => {
|
||||
fs.writeFile(path.join(strapi.config.appPath, 'public', file.key), file.buffer, (err) => {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user