· 6 years ago · Jul 03, 2019, 05:48 PM
1exports.upload = (req, res, next) => {
2 // Init the variables and then read the incoming forms to this endpoint
3 var files = [];
4 var tenantId = req.database;
5 var form = new formidable.IncomingForm();
6 // Parsing the form to get fields and files properly
7 form.parse(req, (err, fields, files) => {
8 count = Object.keys(files).length;
9 var file = files.file.path;
10 // The formidable adds a path to the files variable, so I can read them with the node.js function fs.readFile
11 fs.readFile(file, (err, data) => {
12 // If the function returns err, so I can throw, if not init the AWS S3 class with its own parameters
13 if (err) throw err;
14 const spacesEndpoint = new AWS.Endpoint('nyc3.digitaloceanspaces.com');
15 var s3bucket = new AWS.S3({
16 accessKeyId: ACCESS_KEY,
17 endpoint: spacesEndpoint,
18 secretAccessKey: SECRET_KEY,
19 });
20 // Randomize the name so I can prevent duplicate names
21 var name = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);;
22 var filename = files.file.name;
23 var ext = pathUtil.extname(filename);
24 // Once you have the extension from the filename then create the Bucket if not exists, otherwise upload in the existing bucket
25 s3bucket.createBucket({Bucket: 'touchmobile'}, () => {
26 var params = {
27 Key: 'images/'+tenantId+'/'+name+ext,
28 Body: data,
29 Bucket: 'ingressos',
30 ACL: 'public-read'
31 };
32 s3bucket.upload(params, (err, data) => {
33 fs.unlink(file, err => {
34 if (err) {
35 console.error(err);
36 }
37 });
38
39 if (err) {
40 console.log('error msg: ', err);
41 res.status(500).send(err);
42 } else {
43 console.log("uploaded", data.Location);
44 res.json({'status': 1, 'url': data.Location});
45 req.onSend();
46 }
47 });
48 });
49 });
50 })
51};