Created
February 10, 2022 12:41
-
-
Save blackspike/93712ef559ceba62f2bafb5cee41ff00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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