| 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; | |
| } | |
| } |