Transmit the image produced by the frontend JavaScript

I recently acquired a third-party library that has the capability to generate screenshots.

https://i.sstatic.net/dxEcb.png

I am eager to store these screenshots on my server, and I am currently utilizing Axios. I believe it involves working with blobs, arraybuffers, and more?

  1. What is the process for sending it?

    Axios.post('/api/saveimage', { ??? })

  2. I am utilizing NodeJs express on the backend. How can I save this as an actual image file?

Answer №1

When sending data from the frontend, ensure you follow this structure:

let formData = new FormData()

formData.append("image", file)

axios.post("/api/saveimage",formData)

Firstly, create a FormData and append the file to it. In this example, the file is named image. Next, you will need to use multer on your nodejs backend.

npm i multer

To start, create a middleware:

const multer = require("multer");
const whitelist = ["image/png", "image/jpeg", "image/jpg", "image/webp"];
const storeImages = multer.diskStorage({
  destination: async function (req, file, cb) {
    if (!whitelist.some((type) => type === file.mimetype)) {
      return cb(new Error("File is not allowed"), "/");
    }

    cb(null, "your/destination/path");
  },
  filename(req, file, cb) {
    let [name] = file.originalname.split(".");

    cb(null, name + ".png");
  },
});

exports.uploadImageStorage = multer({
   storage: storeImages,
});

Ensure that your destination path exists and include an extension for your file, such as .png.

Now, create your route:

const { uploadImageStorage } = require("../yourstorage")
app.post("/api/saveimage", uploadImageStorage.single("image"), (req, res) => {
   let file = req.file
   let path = file.path
})

Be sure that the parameter in

uploadImageStorage.single("image")
matches the one used in
formData.append("image", file)
.

You can save the file path in a database and optionally manipulate the image using sharp.

If you have a folder named static with an image like photo.png inside, you would typically access it via localhost:3000/photo.png, not localhost:3000/static/photo.png.

If you encounter this setup, remember to remove static from the path to correctly display the image on the frontend.

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 does Python interpret arrays from JavaScript?

As part of my API setup, I am sending parameters to a python script. One of these parameters happens to be a JavaScript array. Interestingly, when I check the array in Python, it only shows the first index. Here is the snippet of my Angular JS get request ...

Undo changes in Sequelize transaction using a specific rollback target

In my current project, I am utilizing managed transactions. There is a specific scenario where I need to implement a single transaction and revert to a certain savepoint if it encounters an error, but still ensure that the changes are committed in the end. ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

Define the content and appearance of the TD element located at the x (column) and y (row) coordinates within a table

In my database, I have stored the row and column as X and Y coordinates. Is there a straightforward way to write code that can update the text in a specific td element within a table? Here is what I attempted: $('#sTab tr:eq('racks[i].punkt.y&a ...

What is the best way to store numerous objects in an array at once?

Upon clicking the save button, I encounter this object: {description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id: 72, …} However, every time I click on save, a new object ...

The error encountered is related to the MongooseServerSelectionError that occurs in

I have been working on setting up my first mongo-db application to connect to the server. However, I am encountering a specific error during this process: const express = require('express'); const mongoose = require('mongoose'); const ...

Problem with displaying requests at the endpoint on the Express Router

I'm currently delving into the world of express and experimenting with express.Router() to route to various endpoints. Despite following online tutorials diligently, I am only able to successfully send text from the root '/' endpoint and not ...

Tips on stopping Bootstrap Modal from opening when element within trigger is clicked?

I've configured my table rows to trigger a bootstrap modal upon click. However, I have an issue with the select box in each row allowing user selection of status options. Is there a way to prevent the modal from opening when the select box is clic ...

Utilizing Normal Mapping with ShaderMaterial, TangentSpace, and fromGeometry in Three.js

I've been struggling to understand normal mapping with Three.js. Despite my efforts, I can't seem to get it right. Below is the code I've been working on: Javascript: var bufferGeometry = new THREE.BufferGeometry(); bufferGeometry.fromGeo ...

Nodejs express sending file to database or uploading file

I am new to the Express/Node environment and unfamiliar with the APIs and functionalities it offers. In our project, we are using Express 4 and need to implement a feature that includes multiple file upload buttons. We are considering storing the files in ...

Struggling to set up a css3 keyframe slide effect and seeking help to properly configure it. Check out the Fiddle for more details

I am looking to create a responsive version of the animation in this fiddle (link provided below). I want the animation to be 100% wide and have a height of 500px. However, when I adjust the width to 100%, it causes issues at the end of the animation. Can ...

Iterate through the pixels of the canvas to locate the x and y coordinates and position of each white pixel

In my project, I have a canvas with white text drawn on it. To identify the white pixels, I extract the image data and iterate through each pixel using the following code snippet: var pixelData = this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx ...

Enhancing D3 visualization with centralized alignment and mobile-friendly responsiveness

I am still quite new to JavaScript and development in general, so I may be overlooking something obvious. Although I have successfully created a chart using d3, I am struggling with positioning. No matter how much I manipulate it with CSS, the chart just d ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

Require assistance in understanding JSON data in the form of a variable

Apologies for any language barriers, but I have encountered a problem that I need help with. I am trying to create a highchart from an AJAX call. The following code works perfectly: chartOptions = { chart: { renderTo: 'grafica1', type: 'ar ...

Discovering and choosing the appropriate course

I am facing a situation where I need to specifically select an element with the class .foo, but there are two anchor tags, both having the class .foo. However, I only want to select the one without the additional .bar class. How can I achieve this? <a ...

Application featuring a live display of click counts through real-time updates using Socket.IO

If I have an app that displays a button for users to click on, along with a counter showing the total number of clicks from all users, is it possible to update this counter in real-time within the app? I'm considering incorporating Socket.IO technolo ...

JS custom scrollbar thumb size issues in relation to the scroll width of the element

I recently implemented a custom scrollbar for a component on my website. To determine the length of the scrollbar thumb, I use the formula viewportWidth / element.scrollWidth;. This provides me with a percentage value that I then apply to the thumb elemen ...

Karma is unable to locate the module within the specified relative path

I'm facing a challenge with Karma not being able to load a specific file. As a novice in Karma, I dedicated the entire day to researching and checking documentation for similar issues with no luck. Upon initiating the karma process, it encounters an ...

Questions about securing REST APIs

Currently, I am in the process of developing a REST API with Express Js and I have some inquiries related to security. To start off, I am curious about the extent of information hackers can obtain from a request sent from the client side. Is it possible f ...