javascript - Ant设计文件上传中使用customRequest

标签 javascript reactjs antd ant-design-pro

我正在使用 Axios 来处理文件上传。我在显示文件上传的上传进度时遇到问题。我使用的文件上传 View 是“图片卡”。

HTML

<Upload
  accept="image/*"
  customRequest={uploadImage}
  onChange={handleOnChange}
  listType="picture-card"
  fileList={defaultListOfFiles}
  className="image-upload-grid"
>
  {defaultListOfFiles.length >= 8 ? null : <div>Upload Button</div>}
</Upload>

OnChangeHandler
const handleOnChange = ({ file, fileList, event }) => {
  console.log(file, fileList, event);
  //Using Hooks to update the state to the current filelist
  setDefaultFileList(fileList);
  //filelist - [{uid: "-1",url:'Some url to image'}]
};

自定义请求处理程序
const uploadImage = options => {

  const { onSuccess, onError, file, onProgress } = options;

  const fmData = new FormData();
  const config = {
    headers: { "content-type": "multipart/form-data" },
    onUploadProgress: event => {
      console.log((event.loaded / event.total) * 100);
      onProgress({ percent: (event.loaded / event.total) * 100 },file);
    }
  };
  fmData.append("image", file);
  axios
    .post("http://localhost:4000/upload", fmData, config)
    .then(res => {
      onSuccess(file);
      console.log(res);
    })
    .catch(err=>{
      const error = new Error('Some error');
      onError({event:error});
    });
}

最佳答案

antd Upload 使用 rc-upload 在引擎盖下。 onProgress 只接受一个参数。我也用过antd Progress 用于显示进度的另一种方式。阅读更多关于 customRequest .

upload-progress

JSX

import { Upload, Progress } from "antd";

const App = () => {
  const [defaultFileList, setDefaultFileList] = useState([]);
  const [progress, setProgress] = useState(0);

  const uploadImage = async options => {
    const { onSuccess, onError, file, onProgress } = options;

    const fmData = new FormData();
    const config = {
      headers: { "content-type": "multipart/form-data" },
      onUploadProgress: event => {
        const percent = Math.floor((event.loaded / event.total) * 100);
        setProgress(percent);
        if (percent === 100) {
          setTimeout(() => setProgress(0), 1000);
        }
        onProgress({ percent: (event.loaded / event.total) * 100 });
      }
    };
    fmData.append("image", file);
    try {
      const res = await axios.post(
        "https://jsonplaceholder.typicode.com/posts",
        fmData,
        config
      );

      onSuccess("Ok");
      console.log("server res: ", res);
    } catch (err) {
      console.log("Eroor: ", err);
      const error = new Error("Some error");
      onError({ err });
    }
  };

  const handleOnChange = ({ file, fileList, event }) => {
    // console.log(file, fileList, event);
    //Using Hooks to update the state to the current filelist
    setDefaultFileList(fileList);
    //filelist - [{uid: "-1",url:'Some url to image'}]
  };

  return (
    <div class="container">
      <Upload
        accept="image/*"
        customRequest={uploadImage}
        onChange={handleOnChange}
        listType="picture-card"
        defaultFileList={defaultFileList}
        className="image-upload-grid"
      >
        {defaultFileList.length >= 1 ? null : <div>Upload Button</div>}
      </Upload>
      {progress > 0 ? <Progress percent={progress} /> : null}
    </div>
  );
};


这是 demo

关于javascript - Ant设计文件上传中使用customRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128062/

相关文章:

php - 使用散列加查询字符串作为 jquery 插入网页的 anchor ?

reactjs - 如何使用自定义 jss 插入点在 material-ui 中配置 makeStyles Hook ?

javascript - 在for循环中 react Js点击事件

javascript - Ant Design - 按其所有现有数据过滤列

javascript - 难倒未捕获的语法错误 : Unexpected token else,

javascript - 表单内的 <button>

reactjs - Ant Design react - 更改所有组件的默认微调器

reactjs - 如何测试与 Ant Design 的 Popover 内容的交互?

javascript - 根据具有数据属性的类更改宽度/高度

reactjs - 无法访问事件处理函数 : ReactJS 内的 `this.state`