Spaces:
Sleeping
Sleeping
Create lib/uploadImage.js
Browse files- lib/uploadImage.js +39 -0
lib/uploadImage.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const fetch = require('node-fetch');
|
| 2 |
+
const FormData = require('form-data');
|
| 3 |
+
|
| 4 |
+
module.exports = async buffer => {
|
| 5 |
+
try {
|
| 6 |
+
const { fromBuffer } = require('file-type');
|
| 7 |
+
|
| 8 |
+
let fileType = await fromBuffer(buffer);
|
| 9 |
+
if (!fileType) {
|
| 10 |
+
throw new Error('Cannot determine file type');
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
let { ext } = fileType;
|
| 14 |
+
const randomName = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
| 15 |
+
let bodyForm = new FormData();
|
| 16 |
+
bodyForm.append("fileToUpload", buffer, randomName + "." + ext);
|
| 17 |
+
bodyForm.append("reqtype", "fileupload");
|
| 18 |
+
|
| 19 |
+
let res = await fetch("https://cdnme.idnet.my.id/upload", {
|
| 20 |
+
method: "POST",
|
| 21 |
+
body: bodyForm,
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
if (!res.ok) {
|
| 25 |
+
throw new Error(`Upload failed: ${res.status} ${res.statusText}`);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
let data = await res.json();
|
| 29 |
+
|
| 30 |
+
if (data.success && data.url) {
|
| 31 |
+
return data.url;
|
| 32 |
+
} else {
|
| 33 |
+
throw new Error('Upload failed: Invalid response');
|
| 34 |
+
}
|
| 35 |
+
} catch (error) {
|
| 36 |
+
console.error('Upload error:', error);
|
| 37 |
+
throw error;
|
| 38 |
+
}
|
| 39 |
+
}
|