File size: 1,072 Bytes
f97b123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const fetch = require('node-fetch');
const FormData = require('form-data');

module.exports = async buffer => {
  try {
    const { fromBuffer } = require('file-type');
    
    let fileType = await fromBuffer(buffer);
    if (!fileType) {
      throw new Error('Cannot determine file type');
    }
    
    let { ext } = fileType;
    const randomName = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    let bodyForm = new FormData();
    bodyForm.append("fileToUpload", buffer, randomName + "." + ext);
    bodyForm.append("reqtype", "fileupload");

    let res = await fetch("https://cdnme.idnet.my.id/upload", {
      method: "POST",
      body: bodyForm,
    });

    if (!res.ok) {
      throw new Error(`Upload failed: ${res.status} ${res.statusText}`);
    }

    let data = await res.json();
    
    if (data.success && data.url) {
      return data.url;
    } else {
      throw new Error('Upload failed: Invalid response');
    }
  } catch (error) {
    console.error('Upload error:', error);
    throw error;
  }
}