-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfileparser.js
More file actions
87 lines (76 loc) · 2.92 KB
/
fileparser.js
File metadata and controls
87 lines (76 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const formidable = require('formidable');
const { Upload } = require("@aws-sdk/lib-storage");
const { S3Client, S3 } = require("@aws-sdk/client-s3");
const Transform = require('stream').Transform;
const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
const region = process.env.S3_REGION;
const Bucket = process.env.S3_BUCKET;
const parsefile = async (req) => {
return new Promise((resolve, reject) => {
let options = {
maxFileSize: 100 * 1024 * 1024, //100 megabytes converted to bytes,
allowEmptyFiles: false
}
const form = formidable(options);
// method accepts the request and a callback.
form.parse(req, (err, fields, files) => {
// console.log(fields, "====", files)
});
form.on('error', error => {
reject(error.message)
})
form.on('data', data => {
if (data.name === "complete") {
// let statuscode = data.value['$metadata']?.httpStatusCode || 200;
resolve(data.value);
}
})
form.on('fileBegin', (formName, file) => {
file.open = async function () {
this._writeStream = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk)
}
})
this._writeStream.on('error', e => {
form.emit('error', e)
});
// upload to S3
new Upload({
client: new S3Client({
credentials: {
accessKeyId,
secretAccessKey
},
region
}),
params: {
ACL: 'public-read',
Bucket,
Key: `${Date.now().toString()}-${this.originalFilename}`,
Body: this._writeStream
},
tags: [], // optional tags
queueSize: 4, // optional concurrency configuration
partSize: 1024 * 1024 * 5, // optional size of each part, in bytes, at least 5MB
leavePartsOnError: false, // optional manually handle dropped parts
})
.done()
.then(data => {
form.emit('data', { name: "complete", value: data });
}).catch((err) => {
form.emit('error', err);
})
}
file.end = function (cb) {
this._writeStream.on('finish', () => {
this.emit('end')
cb()
})
this._writeStream.end()
}
})
})
}
module.exports = parsefile;