Ways to retrieve an image uploaded on a nestjs server

I am facing an issue with my NestJS server where I have uploaded images but cannot access them as they appear to be some unreadable data. I have tried converting them to a blob and then setting it as an object URL for the image tag, but that also did not work. Here is the upload code:

    @Post('upload')
    @UseInterceptors(FileInterceptor('file',{
        storage: diskStorage({
          destination: './uploads',
          filename: editFileName,
        }),
        fileFilter: imageFileFilter,
      }))
    uploadFile(@UploadedFile() file){
        console.log(file);
        file.filename = file.originalname;
        const response = {
            originalname: file.originalname,
            filename: file.filename,
        }
        return response;
    }

The above code successfully saves the image as "index-53a2.jpg" in the uploads folder. When trying to retrieve the image using a GET request:

@Get()
display(@Res() res){
    res.sendFile('index-53a2.jpg',{ root: './uploads' })
}

the response shows unreadable encoded data.

I used the following code for testing:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'http:/localhost:3000/student/upload',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              console.log(data);
              // location.reload();
            }
          });

        });

      });

      function fun(){
        $.ajax({
            url: 'http://localhost:3000/student',
            success: function(data){
                console.log('s',data);
                let blob = new Blob([data]);
                var objectURL = URL.createObjectURL(blob);
                document.getElementById('img').src = objectURL;
            },
            error: function(data){
                console.log('e',data);
            }
        });
      }
    </script>
  </head>
  <body>
    <img alt="Image" id="img">
    <form enctype= "multipart/form-data" id="abc">
      <input type="file" name="file" required accept="image/*"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
    <button onclick="fun()">Button</button>
  </body>
</html>

This HTML code is just for testing purposes, but my main objective is to use this server to retrieve student image and data from Angular and save it in MongoDB. I need guidance on how to send an image from Angular to NestJS, where to save it (MongoDB or NestJS server), and how to achieve this.

Your help would be greatly appreciated!!! Thank you in advance.

Answer №1

In order to access your files using NestJs, it is necessary to specify the directory for static assets in your main.ts file by utilizing the .useStaticAssets method on your app

app.useStaticAssets(join(__dirname, '..', 'public'), {
    index: false,
    prefix: '/public',
});

Answer №2

I discovered a solution to this issue. The steps involved include appending all the data into formData and sending it as a request from Angular.

let formData = new FormData();
formData.append('image',this.image);

The 'image' attribute is obtained from a function triggered by the onchange event on the input tag that takes an image as input.

onChange(event){
   this.image = event.target.files[0];
}

Afterwards, the data is sent to the backend using our service.

sendReq(formData){
   this.http.post('localhost:3000/your_route',formData);
}

When accessing it from the Nestjs server, the FileInterceptor is utilized.

import { Controller, Get, Post, Res, UploadedFile, UseInterceptors, Body } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { editFileName, imageFileFilter } from './funcs';
import { diskStorage } from 'multer';

@Post('your_route')
@UseInterceptors(FileInterceptor('image',{
        storage: diskStorage({
          destination: './uploads',
          filename: editFileName,
        }),
        fileFilter: imageFileFilter,
      }))
    async func(@UploadedFile() file, @Body() body){
        try{
            body.image = file.filename;
            body.view = false;
            let res = await this.yourService.yourFunc(body);
            return {
                'success': true,
                'data': res
            }
        }
        catch(err){
            console.log(err);
            return {
                'success': false,
                'data': err
            }
        }
    }

const imageFileFilter = (req, file, callback) => {
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
      return callback(new Error('Only image files are allowed!'), false);
    }
    callback(null, true);
  };

 const editFileName = (req, file, callback) => {
    const name = file.originalname.split('.')[0];
    const fileExtName = '.'+file.originalname.split('.')[1];
    const randomName = Array(4)
      .fill(null)
      .map(() => Math.round(Math.random() * 16).toString(16))
      .join('');
    callback(null, `${name}-${randomName}${fileExtName}`);
  };

This process creates an 'uploads' folder in the root directory where uploaded images get saved. The naming convention used here combines the original file name with a sequence of random characters and integers of length 4, but you can customize this logic according to your requirements.

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

Performing a series of get requests in Angular 2

There is a configuration service that retrieves specific information from a JSON file. getConfiguration(key) { return this.http.get('./app/config/development.json').map(res => { this.result = res.json(); return this.result[ke ...

Use `Res.download()` to send data to the client instead of directly downloading the file

I am trying to transfer a file that has been created by my NodeJS server from the server to the client for download. Users input object data which is then stored in a database. The function responsible for creating the file will read these objects and pop ...

What is the best way to deliver pictures to the client?

While working on a website with express.js, I am considering the best way to store images. For certain aspects of the site, such as team pages, we will be using a database. When new team members join, we will update CouchDB with their information and a new ...

I'm having trouble understanding why I keep encountering this error message: "SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…"

I am in the process of implementing a download button feature that will allow users to download a document from my node.js server. Check out this stylish button: https://i.stack.imgur.com/s4CjS.png For the front-end, I am utilizing Angular as the fram ...

Is JavaScript parsed by Node.js before being passed to V8's engine?

Is it accurate to say that Node.js has its own parser and interpreter since V8 does not recognize terms like "require" and "setTimeout"? This would mean that Node.js identifies the non-JavaScript tokens and processes them before passing the rest of the c ...

Utilizing Node.js to create a REST API that allows for seamless communication with a MongoDB database through

Currently, I am developing a web application utilizing the MERN framework (MongoDB, Express, Node.js for back-end, React for front-end). One specific part of my web application requires frequent access to a collection in the MongoDB database (every 50 ms) ...

What is the best way to identify a specific pattern within a string using regular expressions in JavaScript?

Looking for a way to extract specific values from a string? let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.' Desiring an array like this from the string: ['user ...

What are some potential problems that could arise when making a POST request for signing authentication in a MERN stack using JWT?

I'm currently in the process of developing a social media application using the MERN stack. To ensure the functionality of the backend API, I am utilizing POSTMAN. Here is an overview of the dependencies outlined in the package.json file: { "na ...

The NullInjector has issued an error regarding the lack of a provider for the Decimal

I recently integrated lazy loading into my application. However, one of my services is in need of the DecimalPipe. The structure of my modules goes like this: service -> shared module -> App module To give you more context, I have already added "CommonMo ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

"Angular SwtAlert2: The Ultimate Multi-Selection Tool

I am trying to integrate the ng-select directive into SweetAlert2, but the code snippet below is not working as expected: const { value: formValues } = await swal.fire({ title: 'Multiple inputs', html: '<ng-select id=" ...

Exploring Angular 2: Exploring the most effective strategies

I've been working on building a complex Angular2 application and I've run into issues with the UI not updating properly to reflect changes in the application state. I've done a lot of research on how to solve this issue and tried implementin ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Unable to perform a union operation that combines multiple enums into one

Here is a basic example: export enum EnumA { A = 'a', } export enum EnumB { A = 'b', } export class SomeEntity { id: string; type: EnumA | EnumB; } const foo = (seArray: SomeEntity[]) => { seArray.forEach((se) => { ...

Express app: the ideal location to implement a closed-loop temperature control system

I am relatively new to working with express.js, having only created some basic client/server apps in the past. Currently, I am looking to develop a temperature controller using a PID component. However, I am struggling to grasp the architecture of express ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...

Executing npm build within a prebuild script on Vercel to compile a Next.js application

I am in the process of developing a unique Markdown- / MDX-based platform for blogging (take a look at my project on GitHub). I want to give users the ability to incorporate their own React components into the content section of their MDX files. The Chall ...

utilize the Dbus library within an Electron application (Building process)

Encountering an issue when requiring DBus from the dbus package. const { app, BrowserWindow } = require("electron"); const DBus = require('dbus'); app.whenReady().then(() => { var win = new BrowserWindow({ width: 600, height: 50 ...

What is the method for specifying a specific sub-dependency version in a package in Node.js?

Let me simplify my issue for you. I am facing troubles while trying to install two plugins, plugin A version 2.0 and plugin B version 3.0. It turns out that plugin B has plugin A as a sub-dependency with a conflicting version, resulting in a build phase e ...