nestjs 全栈进阶--文件上传

nest new upload -p pnpm
pnpm i multer
pnpm i -D @types/multer

允许跨域

1. 单文件上传

我们去新增一个用于上传的handler

@Post('upload')
@UseInterceptors(FileInterceptor('file', {
    dest: 'uploads'
}))
uploadFile(@UploadedFile() file: Express.Multer.File, @Body() body) {
    console.log('body', body);
    console.log('file', file);
}

使用 FileInterceptor 来获取前端给的 file 字段,然后通过 UploadedFile 装饰器把它作为参数注入,dest是指定图片的存放目录的,当我们执行pnpm run start:dev时,你会发现它给我们自动的创建了一个uploads的文件夹

现在我们去快速写个前端页面,用于上传

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios@1.6.8/dist/axios.min.js"></script>
  </head>
  <body>
    <input id="fileInput" type="file" />
    <script>
      const fileInput = document.querySelector('#fileInput');

      async function formData() {
        const data = new FormData();
        // body字段
        data.set('name','xt');
        data.set('age', 18);
        // 对应后端提取的file字段
        data.set('file', fileInput.files[0]);

        const res = await axios.post('http://localhost:3000/upload', data);
        console.log(res);
      }

      fileInput.onchange = formData;
    </script>
  </body>
</html>

鼠标右键选择这个,在默认浏览器打开,注意:这个功能需要安装vscode插件--》

然后选择文件,上传就好

可以看到,打印了 file 对象,并且文件也保存到了 uploads 目录

2. 多文件上传

我们新写个handler

@Post('uploads')
@UseInterceptors(FilesInterceptor('files', 3,  {
    dest: 'uploads'
}))
uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body) {
    console.log('body', body);
    console.log('file', files);
}

单文件用的是:FileInterceptor,多文件用的是FilesInterceptor,多了一个s

单文件用的是:UploadedFile,多文件用的是UploadedFiles,也多了一个s

这个3,表示最大数量

然后我们改一下前端代码

<input id="fileInput" type="file" multiple />

async function formData() {
    const data = new FormData();
    data.set('name','xt');
    data.set('age', 18);
    [...fileInput.files].forEach(item => {
        data.append('files', item)
    })

    const res = await axios.post('http://localhost:3000/uploads', data);
}

然后我们选择两个文件在上传

3. AnyFilesInterceptor

上面我们不管是单文件,还是多文件,我们都指定获取了一个file字段,那万一我们不知道这个字段是什么呢?这个时候我们就可以使用AnyFilesInterceptor

前端我们修改下请求路径,我们再去试试上传

4. 全局设置路径及处理文件名

刚刚我们都是在路由上指定文件存储位置的,现在我们来试试全局指定

我们再去写个handler试试,

我们在修改下前端的请求路径

我们在上传个文件

5. 预览上传的图片

不知大家还记不记得我们之前讲过的useStaticAssets,它让 nest 服务支持静态文件的访问。

  • useStaticAssets prefix 是虚拟前缀
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {NestExpressApplication} from '@nestjs/platform-express'
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.enableCors()

  app.useStaticAssets(join(__dirname, '../new-uploads'), {
    prefix: '/xt'
  });

  await app.listen(3000);
}
bootstrap();

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
nestjs可以使用modbus-tcp进行读写操作。在nestjs中,可以使用npm包“modbus-serial”来实现modbus-tcp的读写操作。首先需要安装该npm包,然后在nestjs中引入该包并使用其提供的方法进行读写操作。具体实现可以参考以下代码: ```typescript import { Injectable } from '@nestjs/common'; import { ModbusTcpClient } from 'modbus-serial'; @Injectable() export class ModbusService { private client: ModbusTcpClient; constructor() { this.client = new ModbusTcpClient({ host: '127.0.0.1', port: 502, }); } async readCoils(address: number, length: number): Promise<boolean[]> { const result = await this.client.readCoils(address, length); return result.data; } async writeCoil(address: number, value: boolean): Promise<void> { await this.client.writeCoil(address, value); } async readHoldingRegisters(address: number, length: number): Promise<number[]> { const result = await this.client.readHoldingRegisters(address, length); return result.data; } async writeHoldingRegister(address: number, value: number): Promise<void> { await this.client.writeHoldingRegister(address, value); } } ``` 在上述代码中,我们创建了一个名为“ModbusService”的nestjs服务,并在构造函数中初始化了一个modbus-serial的客户端。然后,我们定义了四个方法来实现modbus-tcp的读写操作,分别是“readCoils”、“writeCoil”、“readHoldingRegisters”和“writeHoldingRegister”。这些方法分别用于读取线圈、写入线圈、读取保持寄存器和写入保持寄存器。在这些方法中,我们使用了modbus-serial提供的相应方法来实现读写操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值