简体   繁体   English

如何在 Nestjs 中上传文件到谷歌云存储?

[英]How to Upload a File to Google Cloud Storage in Nestjs?

I was searching on the inte.net for a tutorial on how to upload a file in google storage with nestjs, but I cant find anything.我在 inte.net 上搜索有关如何使用 nestjs 在谷歌存储中上传文件的教程,但我找不到任何东西。 Someone can help me?有人可以帮助我吗?

-how to connect google cloud with nestjs server? - 如何将谷歌云与 nestjs 服务器连接?

-how to upload a file from client side in google cloud with nestjs? - 如何使用 nestjs 从客户端上传文件到谷歌云?

You can follow this URL https://www.npmjs.com/package/@google-cloud/storage .你可以关注这个 URL https://www.npmjs.com/package/@google-cloud/storage

There you can find many sample code for using GCP, such as sample code for uploading files which can be found here https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFile.js .在那里你可以找到许多使用 GCP 的示例代码,例如上传文件的示例代码可以在这里找到https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFile.js

For implementation in NestJS, because NestJS supports dependency injection, we create a provider first.在NestJS中实现,因为NestJS支持依赖注入,所以我们先创建一个provider。

export const GCP_PRODUCT_PHOTO_STORAGE_BUCKET = 'GCP_PRODUCT_PHOTO_STORAGE_BUCKET';

export const gcpProductPhotoStorageProvider: Provider<StorageContract> = 
{
  provide: GCP_PRODUCT_PHOTO_STORAGE_BUCKET,
  useFactory: (configService: ConfigService) => {
    const bucketName = process.env.GOOGLE_PRODUCT_PHOTO_BUCKET;
    const baseUrl = `https://${bucketName}`;

    const bucket = new Storage().bucket(bucketName);
    return new GoogleStorageService(bucket, baseUrl);
  },
  inject: [ConfigService],
};

After we register the provider to the module, then we can immediately use it like this on services.将提供者注册到模块后,我们可以立即在服务上像这样使用它。

import { Bucket } from '@google-cloud/storage';

@Injectable()
export class GoogleStorageService{
  constructor(private readonly bucket: Bucket, private readonly baseUrl: string) {}

  async upload(
    directory: string,
    image: {
      name: string;
      buffer: Buffer;
    },
    metadata?: object,
  ): Promise<string> {
    const filePath = path.join(directory, image.name);
    const file = this.bucket.file(filePath);

    const options = metadata ? { metadata } : undefined;

    await file.save(image.buffer, options);
    const uri = new URL(this.baseUrl);
    if (this.baseUrl.endsWith(this.bucket.name)) {
      uri.pathname = path.join(directory, image.name);
    } else {
      uri.pathname = path.join(this.bucket.name, directory, image.name);
    }
    return uri.toString();
  }
}

Maybe you can't use this answer immediately, but at least it can give you an idea of how GCP works in NestJS.也许你不能立即使用这个答案,但至少它可以让你了解 GCP 在 NestJS 中是如何工作的。

You can use like-fs with like-fs-gcs .您可以将like-fslike-fs-gcs一起使用。 It's a library for accessing Google Cloud Storage using an api very similar to the native fs package.它是一个使用 api 访问 Google Cloud Storage 的库,与本机fs package 非常相似。

It has support to be used as a NestJS module.它支持用作 NestJS 模块。 Here's an example:这是一个例子:

import {GCSFilesystem, GCSFilesystemModule} from "like-fs-gcs";
import {Filesystem} from "like-fs";

@Module({
  imports: [
    GCSFilesystemModule.forRoot({
      storageBucket: 'my-storage-bucket'
    })
  ],
  providers: [
    {provide: Filesystem, useExisting: GCSFilesystem},
    SomeService
  ]
})
export class MyAppModule {

}
import {createReadStream} from 'fs';

@Injectable()
export class SomeService {

  constructor(@Inject(Filesystem) private readonly fs: IOnlineFilesystem) {}

  uploadFile(localFile: string) {
    return this.fs.writeStreamToFile('some/path', createReadStream(localFile))
  }

}

Disclosure: I'm the maintainer of this project披露:我是这个项目的维护者

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM