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 0 You must be signed in to fork a gist
  • Save blackspike/93712ef559ceba62f2bafb5cee41ff00 to your computer and use it in GitHub Desktop.
Save blackspike/93712ef559ceba62f2bafb5cee41ff00 to your computer and use it in GitHub Desktop.
import axios from 'axios'
import formidable from 'formidable'
import fs from 'fs'
import FormData from 'form-data'
// --------------------------------
// Upload image
// --------------------------------
export default async (req, res, next) => {
try {
// We're using formidable to capture our form contents
const form = new formidable.IncomingForm()
// We'll parse the contents of the form that gets sent to our endpoint
form.parse(req, async (err, fields, files) => {
// We'll expect a file called uploadedImage and create a readable stream from its temporary path.
// uploadedImage will be the picture we want to upload
let image = fs.createReadStream(files.uploadedImage.filepath)
// We'll create a new form to send to Cloudflare Images and append our newly processed image
const data = new FormData()
data.append('file', image)
// Finally, we'll use axios to make a POST request to Cloudflare Images
await axios({
method: 'post',
maxContentLength: Infinity,
maxBodyLength: Infinity,
url: `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/images/v1`,
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
...data.getHeaders(),
},
data,
})
.then((response) => {
console.log('Upload Successful')
res.status(200).json({ message: `Success! `, results: response.data })
})
.catch((error) => res.status(500).json({ message: `Fail! `, error }))
})
// return res.status(200).json({ message: `Success!` })
} catch (error) {
console.error(error)
return res.status(500).json({ message: `Fail! `, error })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment