Antd和React使用Upload上传组件自定义上传文件(图片为例)

1.定义结构

             <Upload
                accept="image/*"
                listType="picture-card"
                fileList={fileList}
                onChange={onChange}
                onPreview={onPreview}
                customRequest={handlePreview}
              >
                {fileList.length < 1 && "+ 上传封面"}
              </Upload>

2.内容

import type { GetProp, UploadFile, UploadProps } from "antd";

const [fileList, setFileList] = useState<UploadFile[]>([]);

const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as FileType);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

const handlePreview = async (file: any) => {
    const form = new FormData();
    form.append("file", file.file);
    const res: any = await UploadApi(form);
    console.log("上传结果", res);
    if (res.status === 0) {
      const FileList = [
        {
          uid: "1",
          name: res.name,
          url: res.url,
        },
      ];
      setFileList(FileList);
    }
    return false;
  };

3.nodejs接收(app.js配置)

const multer = require("multer");
let objMulter = multer({ dest: "./public/upload" });
//实例化multer,传递的参数对象,dest表示上传文件的存储路径
app.use(objMulter.any()); //any表示任意类型的文件
// app.use(objMulter.image())//仅允许上传图片类型
app.use(express.static("./public"));

4.定义接口

const fs = require("fs");
async function UploadFile(req, res) {
  console.log("上传内容", req.files);
  const name = Buffer.from(req.files[0].originalname, "latin1").toString(
    "utf8"
  );//nodejs对于中文产生乱码的解决办法
  let oldName = req.files[0].path; //获取名字
  //给新名字加上原来的后缀
  let newName = req.files[0].path + name;
  fs.renameSync(oldName, newName); //改图片的名字
  res.send({
    status: 0,
    name: name,
    url: "http://localhost:6789/upload/" + req.files[0].filename + name, //该图片的预览路径
  });
}

最近更新

  1. TCP协议是安全的吗?

    2024-03-17 18:44:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-17 18:44:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-17 18:44:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-17 18:44:02       18 阅读

热门阅读

  1. 【MySQL】GROUP_CONCAT 运用易错点之建立方程

    2024-03-17 18:44:02       22 阅读
  2. kubeadm部署Kubernetes(k8s) 1.23.0高可用集群

    2024-03-17 18:44:02       21 阅读
  3. 简单理解promise。。。

    2024-03-17 18:44:02       22 阅读
  4. python爬取B站CC字幕(隐藏式字幕)

    2024-03-17 18:44:02       18 阅读
  5. 微服务的无状态、版本控制向后兼容、流量整型

    2024-03-17 18:44:02       16 阅读