ant design通过后端上传文件

2023-09-23 晚上前端 31 次浏览1条评论

前端

import { InboxOutlined } from "@ant-design/icons";
import Dragger from "antd/lib/upload/Dragger";

export default function AppUpload() {
  return (

    <div>
      <Dragger
        accept=".apk"
        action={"http://localhost:5200/api/oss/uploadApp"}
        name="file"
        height={160}
        listType="picture"
        maxCount={1}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或者拖拽文件上传</p>
      </Dragger>
    </div>

  );
}

后端

  @Post('uploadApp')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file) {
    const fileName = `daanjiexi-latest.apk`;
    const res = await this.ossStaticService.uploadFile(
      'app/' + fileName,
      file.buffer,
      file.size,
    );
    return res;
  }

service

import { Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';

@Injectable()
export class OssStaticService {
  private client: any;
  constructor() {
    this.client = new OSS({
      region: process.env.OSS_REGION,
      accessKeyId:  process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret:  process.env.OSS_ACCESS_KEY_SECRET,
      bucket:  process.env.OSS_STATIC_BUCKET,
    });
  }
  public async uploadFile(
    ossPath: string,
    localPath: any,
    size: number,
  ): Promise<string> {
    if (size > 5 * 1024 * 1024) {
      return await this.resumeUpload(ossPath, localPath);
    } else {
      return await this.upload(ossPath, localPath);
    }
  }
  // oss put上传文件
  private async upload(ossPath: string, localPath: string): Promise<string> {
    const res = await this.client.put(ossPath, localPath);
    // 将文件设置为公共可读
    return res.url;
  }

  // oss 断点上传
  private async resumeUpload(
    ossPath: string,
    localPath: string,
  ): Promise<string> {
    let checkPoint: number = 0;
    let res = await this.client.multipartUpload(ossPath, localPath, {
      checkPoint,
      progress: (percent: number, cpt: any) => {
        checkPoint = cpt;
      },
    });
    const url = res.res.requestUrls[0].split('?')[0];
    return url;
  }

  // 获取文件的url
  public async getFileSignatureUrl(filePath: string): Promise<string> {
    if (!filePath) {
      return null;
    }
    const result = await this.client.signatureUrl(filePath, { expires: 36000 });
    return result;
  }

  // 判断文件是否存在
  public async existObject(ossPath: string): Promise<boolean> {
    try {
      const result = await this.client.get(ossPath);
      if (result.res.status === 200) {
        return true;
      }
    } catch (err) {
      if (err.code === 'NoSuchKey') {
        return false;
      }
    }
  }
}


目录

ICP备案号:鲁ICP备2020040322号