I am using next js and have this function on a page to call an api to upload an image i am not sure where to add in a response this does work and uploads the image to my aws cdn.
async function handleProductImageUpload(e) {
const file = e.target.files[0];
const formData = new FormData();
formData.append("file", file);
try {
const upload = await fetch(`/api/image/Upload`, {
method: "POST",
body: formData,
"Content-Type": "image/jpg",
});
const response = await upload.json();
response && console.log(response.data.Location);
setProductImages([...productImages, response.data.Location]);
} catch (error) {
upload.status(error.status).json(error.response.data);
}
}
code for /api/image/Upload
import AWS from "aws-sdk";
export default async function handler(req, res) {
// get the image data
let image = req.body;
// create S3 instance with credentials
const s3 = new AWS.S3({
endpoint: new AWS.Endpoint("https://nyc3.digitaloceanspaces.com/"),
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.ACCESS_SECRET_KEY,
region: "us-west-2",
});
// create parameters for upload
const uploadParams = {
Bucket: process.env.DOS3_BUCKET,
Key: req.query.file,
Body: image,
ContentType: "image/jpeg",
ACL: "public-read",
};
//console.log(uploadParams);
// execute upload
let result = s3.upload(uploadParams, (err, data) => {
if (err) return console.log("reject", err);
else return console.log("resolve", data);
});
res.status(200).send({ result });
}