Skip to content

Instantly share code, notes, and snippets.

@blackspike
Created February 10, 2022 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save blackspike/8b10b417d80e63b357058edd860cb786 to your computer and use it in GitHub Desktop.
Save blackspike/8b10b417d80e63b357058edd860cb786 to your computer and use it in GitHub Desktop.
import axios from 'axios'
import fs from 'fs'
import FormData from 'form-data'
import Busboy from 'busboy'
function parseMultipartForm(event) {
return new Promise((resolve) => {
const fields = {}
const busboy = Busboy({
headers: event.headers,
})
busboy.on('file', (fieldname, filestream, filename, _, mimeType) => {
filestream.on('data', (data) => {
fields[fieldname] = {
content: data,
filename,
type: mimeType,
}
})
})
busboy.on('field', (fieldName, value) => {
fields[fieldName] = value
})
busboy.on('finish', () => {
resolve(fields)
})
busboy.write(Buffer.from(event.body, 'base64').toString('utf8'))
})
}
exports.handler = async function (event, context) {
try{
const fields = await parseMultipartForm(event)
const data = new FormData()
// data.append('file', fields.uploadedImage.content.toString('base64'), { type: 'image/jpeg' })
data.append('file', Buffer.from(fields.uploadedImage.content, 'base64'))
await axios({
method: 'post',
url: `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/images/v1`,
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
'Content-Type': 'multipart/form-data; boundary=' + data._boundary,
},
data
})
.then((response) => {
return {
statusCode: 200,
body: JSON.stringify({ response }),
}
})
.catch((error) => {
console.log({ error })
return {
statusCode: 500,
body: JSON.stringify({ error }),
}
})
} catch (error) {
console.error(error)
return {
statusCode: 500,
body: JSON.stringify({ error }),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment