【图文并茂】ant design pro 如何使用 Upload.Dragger 对接阿里云 oss 上传组件(包含后端)

在这里插入图片描述
在这里插入图片描述
在后台系统中,经常要上传图片吧

我这里用的是 阿里云 oss

因为还是很便宜的。

想要用的,去阿里云注册 个账号开通就行,充个几毛钱,够用你好久的

前端

import React from 'react';
import { Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { request } from '@umijs/max';
import { UploadProps } from 'antd/lib/upload/interface';
import { useIntl } from '@umijs/max';

interface MyUploadProps {
  onFileUpload: (url: string) => void;
  accept?: string; // 使accept属性可选
  defaultFileList?: any;
  multiple?: boolean;
}

const MyUpload: React.FC<MyUploadProps> = ({ onFileUpload, accept, defaultFileList, multiple }) => {
  const intl = useIntl();
  // 定义默认的accept值
  const defaultAccept = '.png,.jpeg,.jpg,.gif';

  const customRequest = async (options: any) => {
    const { onSuccess, onError } = options;
    const formData = new FormData();
    if (Array.isArray(options.file)) {
      options.file.forEach((file: any) => {
        formData.append('file', file);
      });
    } else {
      formData.append('file', options.file);
    }

    try {
      const response = await request<{ success: boolean; data: any }>('/upload', {
        method: 'POST',
        data: formData,
        requestType: 'form',
      });

      console.log('response:', response);

      if (response.success) {
        message.success('上传成功');
        if (onSuccess) {
          onSuccess(response);
        }
        const httpUrl = response.data.signedURL; // 假设返回的signedURL就在data字段中
        onFileUpload(httpUrl);
      } else {
        message.error('上传失败');
        if (onError) {
          onError(new Error('上传失败'));
        }
      }
    } catch (error) {
      message.error('上传异常');
      if (onError) {
        onError(new Error('上传异常'));
      }
    }
  };

  const props: UploadProps = {
    name: 'file',
    multiple: multiple,
    customRequest,
    showUploadList: true,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  return (
    <Upload.Dragger
      {...props}
      listType="picture"
      showUploadList={{ showRemoveIcon: true }}
      multiple={multiple}
      accept={accept || defaultAccept}
      maxCount={multiple ? undefined : 1}
      defaultFileList={defaultFileList}
      style={{ width: 328 }}
    >
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">{intl.formatMessage({ id: 'upload.text' })}</p>
      <p className="ant-upload-hint">{intl.formatMessage({ id: 'upload.hint' })}</p>
    </Upload.Dragger>
  );
};

export default MyUpload;

组件我都封装好了,后面可以直接用。

比如

        <ProForm.Item required label={intl.formatMessage({ id: 'platform.image' })} name="image">
          <MyUpload
            accept="image/*"
            onFileUpload={(data: any) => {
              console.log('Uploaded resource URL:', data);
              setImageUrl(data); // Assuming 'data' is an array of objects with a 'title' property
            }}
            defaultFileList={defaultFileList}
          />
        </ProForm.Item>

后端

export const uploadFileToOSS = handleAsync(async (req: CustomRequest, res: Response) => {
  const file = req.file;

  if (!file) {
    res.status(400);
    throw new Error('No file provided');
  }

  const filePath = file.path; // This now points to the /tmp directory
  const ossPath = `taskOssUploads/${file.filename}`;

  // Read the file from /tmp directory
  const fileContent = fs.readFileSync(filePath);

  // Upload the file content to OSS
  await ossClient.put(ossPath, fileContent);

  // Optionally, delete the file from /tmp directory after uploading
  fs.unlinkSync(filePath);

  // Generate a signed URL with read permission (valid for 1 hour)
  const signedURL = await generateSignedUrlForOSS(ossPath);

  res.json({
    success: true,
    data: { signedURL, file: ossPath },
  });
});

路由地址是这样的:

app.post('/api/upload', handleFileUpload, uploadFileToOSS);
export const uploadFileToS3 = handleAsync(async (req: CustomRequest, res: Response) => {
  const file = req.file;

  if (!file) {
    res.status(400);
    throw new Error('No file provided');
  }

  const bucketName = process.env.AWS_BUCKET_NAME;
  const key = `taskS3Uploads/${file.filename}`;
  const fileContent = fs.readFileSync(file.path);

  // Upload parameters for S3
  const params = {
    Bucket: bucketName,
    Key: key,
    Body: fileContent,
    ContentType: file.mimetype,
  };

  // Upload file to S3
  await s3.upload(params).promise();

  // Use the utility function to generate a signed URL
  const signedURL = await generateSignedUrlForS3(key);

  // Optionally, remove the file from temporary storage
  fs.unlinkSync(file.path);

  // Respond with the signed URL
  res.json({
    success: true,
    message: 'File uploaded successfully',
    data: { signedURL, file: key },
  });
});

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Vue 3 中使用 antd 的 Upload.Dragger 组件,并且给后端传递文件类型,你可以按照以下步骤进行操作: 1. 安装 antd 组件库: ``` npm install antd ``` 2. 在你的代码中引入所需的组件: ```vue <template> <a-upload-dragger :before-upload="beforeUpload"> <p class="ant-upload-drag-icon"> <a-icon :icon="iconType" /> </p> <p class="ant-upload-text">点击或拖动文件到此区域上传</p> <p class="ant-upload-hint">支持单个或批量上传</p> </a-upload-dragger> </template> <script> import { defineComponent, ref } from 'vue'; import { Upload, message } from 'ant-design-vue'; import { InboxOutlined } from '@ant-design/icons'; export default defineComponent({ components: { 'a-upload-dragger': Upload.Dragger, 'a-icon': InboxOutlined, }, setup() { const iconType = ref('inbox'); const beforeUpload = (file) => { // 获取文件类型 const fileType = file.type; // 发送给后端的文件类型参数名为 fileType const formData = new FormData(); formData.append('fileType', fileType); // 发送上传请求给后端 // 使用 axios 或其他 HTTP 库发送 POST 请求 // 例如: // axios.post('/api/upload', formData) // .then(response => { // // 处理上传成功后的逻辑 // }) // .catch(error => { // // 处理上传失败后的逻辑 // }); return false; // 阻止默认的上传行为 }; return { iconType, beforeUpload, }; }, }); </script> <style> .ant-upload-drag-icon { color: #1890ff; } </style> ``` 在上述代码中,我们使用antd 的 Upload.Dragger 组件来创建一个拖拽上传的区域。通过设置 before-upload 属性来处理文件上传前的逻辑。 在 beforeUpload 方法中,我们可以获取到上传的文件对象 file,通过 file.type 可以获取到文件的类型。然后,我们创建一个 FormData 对象,并将文件类型参数名为 fileType 添加到 FormData 中。 最后,我们发送 POST 请求给后端,将 FormData 作为请求体发送给后端,并处理上传成功或失败的逻辑。 请注意,这里的上传逻辑仅为示例,具体的后端处理逻辑需要根据你的后端框架来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员随风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值