1

I am using nestjs and react js to make an image uploader. For react i use this:

 const props = {
        onChange({ file, fileList }: any) {
            const fd = new FormData();
            fd.append('img', fileList[0].originFileObj);
            fetch('http://localhost:3000/upload', {
                method: 'POST',
                body: fd,
            })
                .then(async response => {
                    const data = await response.json();
                    console.log(data)
                })
                .catch(error => {
                    message.error('There was an error!', error);
                });
        },
        defaultFileList: [

        ],
    };


    return (
        <div>
            <Form
                name="form"
                className="form"
            >
            <Form.Item
                className="upload"
                valuePropName="fileList"
            >
                <Upload {...props}>
                    <Button>Upload</Button>
                </Upload>
            </Form.Item>
            </Form>
        </div>
    );
};

For NestJs i use:

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post('/upload')
  @UseInterceptors(
    FileInterceptor('img', {
      dest: './uploads',
    }),
  )
  uploadFile(@UploadedFile() file) {
    console.log(file, 'file');
  }
}

In console.log(file, 'file'); i get:

{
  fieldname: 'img',
  originalname: 'Full.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './uploads',
  filename: '3c45cd07145707ec09235c7bf3954d7f',
  path: 'uploads\\3c45cd07145707ec09235c7bf3954d7f',
  size: 60655
} 

Question: Which info from the object above should i send back to front end and which to store in database?
Note: Now, in uploads folder in NestJs application i store 3c45cd07145707ec09235c7bf3954d7f after uploading the image. How i know, i should send data on my server and the server should return the valid file(image).
Who can help?

1 Answer 1

1
+100

First of all, I suggest you save your files with the original extension appended to a unique file name, like 3c45cd07145707ec09235c7bf3954d7f.jpg. This is because you usually will want to serve this file statically without doing additional logic. If you don't save it with the extension, you will have to assign mimetype yourself when serving the file.

You can add extension to the filename with a custom callback:

    FileInterceptor('img', {
      dest: './uploads',
      filename: (req: any, file: any, cb: any) => {
        cb(null, `${generateRandomUUID()}${extname(file.originalname)}`);
      },
    })

This filename is all you need to access everything about this file. If you want, you can store this in the database, along with the original file name, size, mimeType, encoding etc.

It will be enough if you send the filename to the frontend. Then, frontend can do a GET request to /uploads/3c45cd07145707ec09235c7bf3954d7f.jpg and it will have its image. You need to either statically serve the uploads directory, or you can create an endpoint like /uploads/:filename if you want to do additional logic before serving the file.

Sign up to request clarification or add additional context in comments.

4 Comments

Your answer really helped me. One question, if i will store every time my images in the uploads folder on the server, how many images i will be able to store? Is it not a bad practice or it is ok? And why should i store the data about images If you want, you can store this in the database, along with the original file name, size, mimeType, encoding etc, in the DB, what could be the purpose?
@Asking you can store as much as there is space in the HDD. Is it a bad practice, depends on your use case. If you are gonna keep those files forever, this is ok. If not, you may want to run a check periodically to remove unused files. Because a user may upload a file but not use it. The purpose of saving that data, again depends on your use case. Let's say you have a CMS for uploaded files in frontend. You may want to order files by their file size. If that happens, it is easier to use DB instead of file system. You may also want to keep original file names for better identification.
related to storing image in DB. If i want to store it in DB what data should i store there? This 3c45cd07145707ec09235c7bf3954d7f.jpg? And if in the situation if i store images in file system i should serve the data on UI, how to send images on UI if i will store data in DB without storing in file system? Thanks.
@Asking you need to store the file itself in the file system and serve it from there. In addition to that, you can store the name of the file in the DB, along with other data about the file. But that is optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.