I am working on a Next.js project where users have the ability to upload images. These images are stored in the public directory. Is there a way for me to access these files using a URL structure like mydomain.com/public/coverimg/image.jpg?
Below is my API code:
import { rejects } from 'assert';
import { resolve } from 'path';
import { promises } from 'stream';
const fs = require('fs');
const moment = require('moment');
const formidable = require('formidable-serverless');
var slugify = require('slugify');
const path = require('path');
const crypto = require('crypto');
export const config = {
api: {
bodyParser: false,
},
};
const handler = async (req, res) => {
const timeStamp = moment().format('DD_MM_YYYY');
const imageId = crypto.randomBytes(16).toString('hex');
fs.mkdir(
`./public/coverimg/${timeStamp}`,
{ recursive: true },
function (err) {
res.send(err);
}
);
const data = await new Promise((resolve, rejects) => {
const form = formidable({
multple: false,
uploadDir: `./public/coverimg/${timeStamp}`,
});
form.keepExtensions = true;
form.keepFileName = true;
form.maxFields = 1000;
form.on('fileBegin', function (name, file) {
file.path = path.join(
`./public/coverimg/${timeStamp}`,
imageId + '_' + slugify(file.name)
);
});
// console.log(data);
form.parse(req, (error, fields, files) => {
if (error) return rejects(error);
resolve(files);
});
});
};
export default handler;