JS Code Snippet
//JS Code Snippet//
/* If you are using CommonJS, use the following modules:
file-type version "16.5.3"
node-fetch version "2.6.0" */
async function uploader(buffer) {
let { ext } = await type.fromBuffer(buffer);
bodyForm = new FormData();
bodyForm.append("file", buffer, "file." + ext);
let response = await fetch("https://baseurl.com/api/upload.php", {
method: "post",
body: bodyForm,
});
return {
status: response.status,
result: (await response.json()).result,
};
}
module.exports = { uploader }
Call Function
// Call Function
const { uploader } = require('../lib/uploader')
const { getBuffer } = require('../lib/function')
const link = `https://example.com/img.jpg`
var buf = await getBuffer(link)
let res = await uploader(buf)
console.log(res)
Function getBuffer
// getBuffer
const axios = require('axios');
const FileType = require('file-type');
const fetch = require('node-fetch');
const getBuffer = async (url, options) => {
try {
options ? options : {}
const res = await axios({
method: "get",
url,
headers: {
'DNT': 1,
'Upgrade-Insecure-Request': 1
},
...options,
responseType: 'arraybuffer'
})
return res.data
} catch (e) {
console.log(`Error : ${e}`)
}
}
module.exports = { getBuffer }
Endpoint List
Endpoint | Description | Status |
---|---|---|
/api/upload.php | Upload Files with buffer. | true |
/file/mimetype | Mime type of the file | true |
Sample Library
const fetch = require('node-fetch')
const FormData = require('form-data')
const { fromBuffer } = require('file-type')
/**
* Upload image to url
* Supported mimetype:
* - `image/jpeg`
* - `image/jpg`
* - `image/png`s
* - `video/mp4`s
* - `all files`
* @param {Buffer} buffer Image Buffer
*/
module.exports = async buffer => {
let { ext } = await fromBuffer(buffer);
let bodyForm = new FormData();
bodyForm.append("file", buffer, "file." + ext);
let res = await fetch("https://baseurl.com/api/upload.php", {
method: "post",
body: bodyForm,
});
let data = await res.json();
let resultUrl = data.result ? data.result.url : '';
return resultUrl;
}
Issues
If you encounter any problems, please contact me by contacting me on GitHub, I will be happy to answer any questions you have.