简体   繁体   English

我想在上传到 nestjs 中的 cloudinary 后返回一组图像链接的响应

[英]i want to return a response of an array of image links after uploading to cloudinary in nestjs

so i need a way to delay the return statement in the controller until the foreach loop is done.所以我需要一种方法来延迟 controller 中的 return 语句,直到 foreach 循环完成。 i just need to properly handle the asynchronous operation and i don't know how else我只需要正确处理异步操作,我不知道怎么办

the response returns an empty array because the array is populated after the response is returned响应返回一个空数组,因为数组是在返回响应后填充的

uploads.controller.ts上传.controller.ts

import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFiles,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadsService } from './uploads.service';
import { v2 as cloudinary } from 'cloudinary';

@Controller('attachments')
export class UploadsController {
  constructor(private readonly uploadsService: UploadsService) {}

  @Post('images')
  @UseInterceptors(FilesInterceptor('attachment'))
  async uploadFile(@UploadedFiles() attachment: Array<Express.Multer.File>) {
    cloudinary.config({
      cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
      api_key: process.env.CLOUDINARY_API_KEY,
      api_secret: process.env.CLOUDINARY_API_SECRET,
      secure: true,
    });
    const response = [];
    await attachment.forEach(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      response.push(fileResponse.secure_url);
      console.log('1', response);
    });
    console.log('2', response);
    return await response;
  }
}

uploads.service.ts上传.service.ts

import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary';
import toStream = require('buffer-to-stream');

@Injectable()
export class UploadsService {
  async uploadImage(
    file: Express.Multer.File,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      const upload = v2.uploader.upload_stream((error, result) => {
        if (error) return reject(error);
        resolve(result);
      });

      toStream(file.buffer).pipe(upload);
    });
  }
}

The problem is here.问题就在这里。

 await attachment.forEach(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      response.push(fileResponse.secure_url);
      console.log('1', response);
    });

Don't pass async function to Array.forEach .不要将 async function 传递给Array.forEach Check out this question .看看这个问题

This will work.这会起作用。

 const response = await Promise.all(attachment.map(async (file) => {
      const fileResponse = await this.uploadsService.uploadImage(file);
      return fileResponse.secure_url;
    }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将文件上传到 cloudinary nestjs 后不返回文件实例 - Not returning the file instance after uploading the files to cloudinary nestjs Cloudinary jQuery File Upload-选择后未上传图像 - Cloudinary jQuery File Upload - image not uploading after selection 使用 Jquery 将图像上传到 cloudinary? - Uploading image to the cloudinary using Jquery? 使用 REST API 上传后“cors”类型的云响应不正确(来自 React) - Incorrect cloudinary response of type "cors" after uploading using REST API (from React) 在Cloudinary中使用ngf-resize上传图像 - uploading image using ngf-resize in Cloudinary Cloudinary Base64在angularjs中上传图片 - Cloudinary Base64 Image uploading in angularjs 如何减少节点 js 中 cloudinary 中图像的上传时间? - How do i reduce the uploading time of image in cloudinary from node js? 将图像上传到cloudinary服务器时如何更改图像名称? - how can I change the name of my image when uploading it to the cloudinary server? 我想从包含图像 react-native 的链接/网址的数组中返回平面列表中的图像 - I want to return images in flatlist from an array that contians links/urls for images react-native 将图像上传到服务器后,如何返回该图像的数据库ID - After Uploading an image to the server, how do i return the database ID for that Image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM