【问题标题】:how to use cloudinary with ant designs upload component?如何将 cloudinary 与 ant 设计上传组件一起使用?
【发布时间】:2021-11-02 17:20:00
【问题描述】:

当我上传文件时,我正在尝试使用 cloudinary 来托管所有图像数据,但我不断收到 AjaxUploader Uncaught (in promise) TypeError: request is not a function error。我很难弄清楚如何将它与我从官方文档中获得的 ant 设计上传组件一起使用。它应该能够上传最多 5 个文件,如果还有更多,它会有条件地取消渲染上传按钮,我已经完成了。我只是不知道如何处理 customRequest 属性,我所有的工作都在 serverUpload 函数上完成。这是沙盒的链接:https://codesandbox.io/s/happy-sun-n9uus?file=/src/App.js

import React, { useState } from "react";
import Modal from "react-modal";
import { Form, Input, Button, Upload, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import axios from "axios";
import cloudinaryInfo from "./cloudinaryInfo/config.js";

const layout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
};
/* eslint-disable no-template-curly-in-string */

const validateMessages = {
  required: "${label} is required!",
  types: {
    email: "Your email is not a valid email!"
  }
};
/* eslint-enable no-template-curly-in-string */

const Question = ({ questionObj, productObj, updatedDataList }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [imageFilesList, setImageFilesList] = useState([]);

  const toggleModal = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsModalOpen(!isModalOpen);
  };

  const serverUpload = async (options) => {
    const { onSuccess, file, onError, onProgress } = options;
    console.log("imageFilesList: ", imageFilesList);
    try {
      const result = await Promise.all([]);
      for (let i = 0; i < imageFilesList.length; i++) {
        let file = imageFilesList[i];
        console.log("FILE: ", file);
        const formData = new FormData();
        formData.append("file", file);
        formData.append(
          "upload_preset",
          cloudinaryInfo.CLOUDINARY_UPLOAD_PRESET
        );
        result.push(
          axios.post(cloudinaryInfo.CLOUDINARY_IMAGE_UPLOAD_URL, formData)
        );
      }
      onSuccess("ok");
    } catch (err) {
      console.log(err);
      onError(err);
    }
  };

  const uploadProps = {
    name: "file",
    customRequest: { serverUpload },
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log("Not uploading ", info.file, info.fileList);
      }
      if (info.file.status === "done") {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} file upload failed.`);
      }
      setImageFilesList(info.fileList);
    },
    listType: "picture",
    maxCount: 5,
    multiple: true,
    onDrop: true
  };

  const modalContent = (
    <Form
      {...layout}
      name="nest-messages"
      onFinish={(values) => console.log(values)}
      validateMessages={validateMessages}
    >
      <Upload {...uploadProps}>
        {imageFilesList.length < 5 && (
          <Button icon={<UploadOutlined />}>Upload (Max: 5)</Button>
        )}
      </Upload>
      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );

  return (
    <div className="question">
      <button onClick={(e) => toggleModal(e)}>Open Modal</button>
      <hr style={{ height: 0.5, borderColor: "red" }} />
      {isModalOpen && (
        <div className="openPanel">
          <Modal
            isOpen={isModalOpen}
            onRequestClose={(e) => toggleModal(e)}
            ariaHideApp={false}
            style={{
              overlay: {
                backgroundColor: "grey"
              }
            }}
          >
            {modalContent}
            <Button onClick={(e) => toggleModal(e)}>Close</Button>
          </Modal>
        </div>
      )}
    </div>
  );
};

export default Question;

【问题讨论】:

  • axios.post 通话中,您使用的网址是否有效?或'mylink'......错误在你的axios调用的catch块中说明了什么
  • 是的,这是一个有效的链接,我只是不想将它分享给公众。我明白了,VM3050:1 POST api.cloudinary.com/v1_1/mycloudname/image/upload 400(错误请求)
  • @RonnyFitzgerald,通常你应该得到更多关于为什么这是一个错误请求的信息。您介意用您的 cloud_name 向 support@cloudinary.com 开票吗,至少我们可以进一步调查?
  • @LoicVdB 我创建了一个 react-app 操场来测试 cloudinary 而没有 ant 设计,只上传单个文件,它可以工作,所以我认为问题不在于 cloudinarys,这就是我结合的方式它与 ant 设计的上传组件会产生问题

标签: javascript reactjs antd cloudinary


【解决方案1】:

serverUpload() 是处理请求的自定义函数。你不把它传递给action prop,你必须把它传递给antd upload customRequest prop,这就是自定义请求的地方。

action 属性用于接受文件的 URL,一旦您对 antd 的上传默认操作进行任何修改,您必须使用 customRequest

here

【讨论】:

  • 好的,所以我将属性更改为自定义请求并将对象 { onSuccess, onError, file, onProgress } 传递到我的 serverUpload 函数中。我是否只需要在 then 和 catch 块中分别调用 OnSuccess 和 onError,因为我已经拥有 imageFilesList 挂钩中的文件?
  • 我得到一个 AjaxUploader.js:320 Uncaught (in promise) TypeError: request is not a function at AjaxUploader2.post after doing that
  • 您可能会收到错误消息,因为您使用forEach 进行 API 调用,并且未捕获承诺。查看建议的解决方案here。当所有调用都成功后,您可以调用onSucess("ok") 让 antd 知道请求成功。你可以将错误传递给onError,就像onError({ err })一样。您可以查看演示 here
  • 我使用了 for 循环而不是 forEach 我什至尝试一次执行一个文件,但我仍然得到未捕获的 promise 错误
  • @RonnyFitzgerald 你能把你的代码示例分享给沙箱之类的吗,让我看看。
猜你喜欢
  • 2015-06-20
  • 2017-06-17
  • 1970-01-01
  • 2020-01-27
  • 2016-01-03
  • 2014-09-15
  • 2020-12-29
  • 2016-03-25
  • 2017-12-18
相关资源
最近更新 更多