Source Code
uploader.js
Code Explanation
This JavaScript code is a function for uploading files (such as images or videos) to a server via API. This function is designed to be used in a Node.js environment.
-
Module Imports
The code imports three required libraries:
- node-fetch: For sending HTTP requests to the server.
- form-data: For creating form data containing the file.
- file-type: For detecting file type (e.g., JPG or PNG) from raw data.
-
Documentation
Code comments explain that this function supports files like
image/jpeg
,image/png
,video/mp4
, and others. The function acceptsbuffer
(raw file data) as input. -
File Type Detection
The
fromBuffer
function is used to determine the file extension (e.g.,jpg
,png
) from the buffer. This is important to ensure the file is processed correctly. -
Creating Form Data
The file data is inserted into a
FormData
object with the namefile
and the appropriate extension. This allows the file to be sent as part of a multipart/form-data request. -
Sending the File
The
fetch
function sends the file to the URLhttps://file.idnet.my.id/api/upload.php
using the POST method. Appropriate headers are included to ensure the server recognizes the content type. -
Retrieving the Result
The server returns a response in JSON format, and the code retrieves the uploaded file URL from
result.file.url
. This function returns the URL that can be used to access the uploaded file.
Important Note
This code requires a Node.js environment and libraries like node-fetch
. Make sure the API URL is still active before using this code. To run it, install dependencies with npm install node-fetch form-data file-type
.
Usage Tips
This function can be used to upload various types of media files. Ensure the buffer you provide is valid file data and not encrypted. To read files from disk, you can use fs.readFile
from Node.js's built-in module.