by 雪隐 from https://juejin.cn/user/1433418895994094
本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可联系授权
你出现在我的页面上是因为你可能正在尝试使用NestJs和Fastify创建一个文件上传端点。不幸的是,有很多令人困惑的内容,有些用你从未听说过的功能和包来创造一些魔力,有些已经过时了,有些只是在试图理解时伤了我的大脑。
编码应该变得简单
幸运的是,我提出了一个简单的解决方案,该解决方案使用NodeJS的基本原理,只需一个额外的包就可以无缝地将文件存储为API的输入。
让我们开始吧!
第一步
添加一个新的包,Fastify/multipart其将用于处理multipart-form数据。我们在这个例子中使用了pnpm,但如果你的项目使用的是npm,那就继续使用吧。
pnpm i @fastify/multipart
第二步
将multipart对象导入并在您的NestJs应用中注册。
在您调用app.listen之前,使用 register 函数在 Fastify 适配器中引入这个包。
// main.ts
import multipart from '@fastify/multipart';
......
await app.register(multipart);
第三步
在您的控制器中,创建一个新的路由来上传文件。确定您导入了fs包,在NodeJS它是一个核心对象主要是来处理文件流的。
在这个方法里面,我将会使用request.files()从请求中取出所有文件。如果您只有一个文件,您可以使用request.file()。
此函数将从请求对象中提取multi-part数据作为FileStream。由于file.file是一个FileStream对象,您可以将一个写流附加到该对象,并将其内容管道传输到本地磁盘位置!(只需确保先创建此文件夹即可。)
// controller.ts
import * as fs from 'fs';
import { Post, Request } from '@nestjs/common';
... inside your class ...
@Post('/upload')
public async upload2Files(@Request() request) {
// extract the files from the request object
const files = request.files();
// iterate through the array of files
for await (const file of files) {
// create a write stream to the location to store the file
const writeStream = fs.createWriteStream(`./document-upload-storage/${file.filename}`);
// take the FileStream object from the files array, and pipe to the write location.
file.file.pipe(writeStream);
}
return { message: 'files uploaded' };
}
... end of class ...
测试一下:
就是这样!非常感谢。
如果你觉得这篇文章有帮助,请点赞和评论,谢谢大家!