Google Cloud Storage Multer Upload Multiple Files

This guide will testify you how you can implement file uploading into your Nestjs application and the things you should keep in mind when doing so. Yous will develop an application with three endpoints that will to the following:

  • Upload an image
  • Upload multiple images
  • Go the prototype using the epitome path

You will too add custom utilities to edit the file name and validate the file upload for images.

So without wasting any farther time let'due south get into it.

Setup

The commencement thing you need to practice is create a Nestjs project that volition hold our Fileserver. For that, you need to open your terminal and run the post-obit command:

          nest new nest-file-uploading && cd nest-file-uploading        

This creates a new directory chosen nest-file-uploading and initializes it with a standard Nestjs configuration.

With the directory in place, you can go ahead and install the needed dependencies for the application using the following commands:

          npm install @nestjs/platform-express --save npm install @types/express -D        

The concluding thing you need to do before jumping into coding is creating the files and folders needed for the projection. This is very simple because the application only needs ane more than file.

          mkdir src/utils affect src/utils/file-uploading.utils.ts        

To start the app, you can now execute npm run commencement:dev in your terminal.

Uploading files

Now that you have completed the setup process, y'all can become ahead and kickoff implementing the actual functionality. Let'southward start by importing the MulterModule in your AppModule so yous can employ Multer in your other files.

          import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { MulterModule } from '@nestjs/platform-express';  @Module({   imports: [MulterModule.register({     dest: './files',   })],   controllers: [AppController], }) consign course AppModule {}        

Here you import the MulterModule from @nestjs/platform-express and add it to your imports statement. Y'all too define the destination in which the files will be saved when an upload occurs.

Note: This destination starts at the root path of the projection, not the src folder.

The next footstep is to implement the actual uploading functionality which is rather simple. Y'all simply demand to add a FileInterceptor() to a normal mail asking handler and then pull out the file from the request using the @UploadedFile() decorator.

          @Post() @UseInterceptors( 	FileInterceptor('image'), ) async uploadedFile(@UploadedFile() file) {     const response = {     	originalname: file.originalname,     	filename: file.filename,     };     return response; }        

The FileInterceptor takes two arguments, a fieldName and an optional options object which you will utilize subsequently to cheque for the correct file types and requite the file a custom name in the directory.

Uploading multiple files at once is almost the same, you but demand to use the FilesInterceptor instead and pass an extra argument of the maximum number of files.

          @Post('multiple') @UseInterceptors(   FilesInterceptor('epitome', 20, {     storage: diskStorage({       destination: './files',       filename: editFileName,     }),     fileFilter: imageFileFilter,   }), ) async uploadMultipleFiles(@UploadedFiles() files) {   const response = [];   files.forEach(file => {     const fileReponse = {       originalname: file.originalname,       filename: file.filename,     };     response.push(fileReponse);   });   return response; }        

That was elementary, the only problem here is that the user can upload every filetype regardless of the file extention which doesn't accommodate all projects and that the filename is just some random number.

Let's fix that by implementing some utilities in your file-upload.utils.ts file.

First, let's implement and file blazon filter which simply allows images to be uploaded.

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

Here y'all create a middleware function which checks if the file type is an paradigm. If so information technology returns true and the image will be uploaded and if non you throw an mistake and return false for the callback.

The editFileName role has the same structure but creates a custom filename using the original name, the file extension and four random numbers.

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

Now that you take created these ii middleware functions it's time to use them in your app.controller.ts file. For that you just demand to add together an extra configuration object to the FileInterceptor which and then looks like this:

                      @Post()   @UseInterceptors(     FileInterceptor('paradigm', {       storage: diskStorage({         destination: './files',         filename: editFileName,       }),       fileFilter: imageFileFilter,     }),   )   async uploadedFile(@UploadedFile() file) {     const response = {       originalname: file.originalname,       filename: file.filename,     };     return response;   }    @Post('multiple')   @UseInterceptors(     FilesInterceptor('paradigm', twenty, {       storage: diskStorage({         destination: './files',         filename: editFileName,       }),       fileFilter: imageFileFilter,     }),   )   async uploadMultipleFiles(@UploadedFiles() files) {     const response = [];     files.forEach(file => {       const fileReponse = {         originalname: file.originalname,         filename: file.filename,       };       response.button(fileReponse);     });     return response;   }        

Lastly you will add a go route which volition take the imagepath equally an statement and return the epitome using the sendFile method.

          @Get(':imgpath') seeUploadedFile(@Param('imgpath') image, @Res() res) {   return res.sendFile(prototype, { root: './files' }); }        

Testing the application

Now that you take finished your awarding information technology's time to examination information technology by sending an HTTP request to your endpoint. This can be done using the curl command in the terminal or by using an HTTP client software like Postman or Insomnia. I personally apply Insomnia only it should be almost the same in Postman.

Start the server using the post-obit command:

          npm run starting time        

As indicated past the concluding output, the server is now running on http://localhost:3000. To exam the API you now merely need to create a new HTTP request and alter the asking body to multipart then y'all can upload files.

Upload images
Upload images

Here you gear up the destination to http://localhost:3000 and add an image to the request body. This can be done past clicking on the arrow side by side to the checkbox and selecting file.

On the right, y'all can encounter the response with the original file name and the new filename on the server.

Note: The new filename is later used to get the images from the server.

Upload multiple images
Upload multiple images

Here you practise the aforementioned but upload multiple files on the /multiple endpoint.

Get uploaded image
Get uploaded image

Getting files is also a simple procedure. You just need to send a get asking to the API with the filename you got from the post asking as a parameter.

The full code for the project can also exist found on my Github.

Conclusion

You  fabricated information technology all the way until the end! Promise that this commodity helped yous sympathize file uploading in Nestjs.

If  you have found this useful, delight consider recommending and sharing it  with other fellow developers. If y'all have any questions or feedback,  permit me know on twitter or use my contact form.

harmonturam1956.blogspot.com

Source: https://gabrieltanner.org/blog/nestjs-file-uploading-using-multer

0 Response to "Google Cloud Storage Multer Upload Multiple Files"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel