Discovering the method to retrieve files from the public folder via URL in next.js

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;

Answer №1

To properly share a URL, use the following format:

{YOUR_WEBSITE}/{IMAGE_NAME}.{FILE_FORMAT}

For instance:

https://example.com/1676292852306cle2thet7000iv73y7xk39o2d.png

Please remember not to include /public/ in the shared URL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

What are some alternative methods for organizing folder structure in Express Handlebars when managing views?

Is there a more efficient way to render HTML files without constantly needing them to have different names? I'm looking for a method where handlebars can identify which file in which folder to render, without encountering conflicts with files of the s ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Visual Studio Code's Intellisense is capable of detecting overloaded functions in JavaScript

What is the best way to create a JavaScript overload function that can be recognized by Visual Studio Code IntelliSense, and how can this be properly documented? A good example to reference is Jasmine's it() function shown below: function it(expecta ...

Developing instance members and methods in JavaScript

After encountering a challenge with creating "private" instance variables in JavaScript, I stumbled upon this discussion. Prior to posing my question, I wanted to provide a thorough overview of the problem. My goal is to showcase a complete example of corr ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Nextjs compatibility with React slick

For my upcoming project in Next.js, I'm considering incorporating the React-slick library for an image slider. However, I've encountered a problem during the installation process. I attempted to install "react-slick" and "slick-carousel" as outl ...

Print out the data on the webpage that was sent via AJAX

I am currently working on a project where I need to create a web page that takes a number as input and searches for its corresponding name in the database. The challenge is to display the name on the page without reloading it. However, the problem is tha ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

The resolvers contain the Query.Mutation but it is not specified in the schema

const { ApolloServer, gql } = require('apollo-server-express'); const express = require('express'); const port = process.env.PORT || 4000; const notes = [ { id: '1', content: 'This is a note', author: 'Adam ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Ajax is not able to trigger a POST request to a PHP form

My form is not posting for some unknown reason, despite everything else on my server functioning properly. Below is the code snippet in question: PHP <?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Cufon failing to load following an ajax call

At first, cufon is used to replace the text on the main page. However, when another page file is loaded, cufon does not apply its replacement to the newly loaded content. Why is that? I tried adding cufon.refresh(); as the last function in the chain. I c ...