Vladon305
Vladon305

Reputation: 43

How to save a picture in nestjs by url

I need to get a link and save the image in the static folder.

Here's what I did

@Injectable()
export class FilesService {

createFileFromUrl(url: string) {
    try {
      const fileName = uuid.v4() + '.jpg';
      const filePath = path.resolve(__dirname, '..', 'static');
      axios({
        url,
        responseType: 'stream',
      }).then(
        (response) =>
          new Promise<void>((resolve, reject) => {
            response.data
              .pipe(fs.createWriteStream(filePath))
              .on('finish', () => resolve())
              .on('error', (e) => reject(e));
          }),
      );
      return fileName;
    } catch (e) {
      throw new HttpException(
        'Произошла ошибка при записи файла',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}

It`s not right? I don't understand why

I`m using this function in controller

I don't understand how this function works, it doesn't return a promise.

How a can made functionality: get and save the image by url in the static folder.

Upvotes: 1

Views: 2210

Answers (1)

Sparko Sol
Sparko Sol

Reputation: 717

Here is the solution. I hope it would help.

  import * as https from 'https';
  import * as fs from 'fs';

  const download = function (url, dest, cb) {
     const file = fs.createWriteStream(dest);
     https
     .get(url, function (response) {
      response.pipe(file);
      file.on('finish', function () {
      file.close(cb); // close() is async, call cb after close completes.
      });
    })
     .on('error', function (err) {
      // Handle errors
      fs.unlink(dest, cb(err.message)); // Delete the file async. (But we don't check the result)
      });
     };

  download(
   'https://img.freepik.com/free-vector/sketchy-sport-balls_1010-37.jpg?w=740&t=st=1668149007~exp=1668149607~hmac=9a00e87ed9d1e646e1faea885ee27826e99281da76f52f372f0b4dda048ee648',                                
    join(process.cwd(), '..', 'static', 'sketchy-sport-balls.jpg'),
    function () {
       console.log('File downloaded');
      },
    );

Change it according to your requirements if you like

Upvotes: 2

Related Questions