当前位置:   article > 正文

antd上传upload组件customRequest 图片转base64_antdsign的upload如何转化为base64

antdsign的upload如何转化为base64

工作有那么个需求,从官网 issue中获悉:

使用 Upload 的 customRequestFileReader 读取。

customRequest

从官网获悉其参数:

onProgress: (event: { percent: number }): void
onError: (event: Error, body?: Object): void
onSuccess: (body: Object): void
data: Object
filename: String
file: File
withCredentials: Boolean
action: String
headers: Object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

具体代码:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Upload, message, Button, Icon } from "antd";

/**
	获取file,通过FileReader获取图片的 base64
*/ 
function customRequest(option) {
  const formData = new FormData();
  formData.append("files[]", option.file);
  const reader = new FileReader();
  reader.readAsDataURL(option.file);
  reader.onloadend = function(e) {
    console.log(e.target.result);// 打印图片的base64
    if (e && e.target && e.target.result) {
      option.onSuccess();
    }
  };
}

/***
	上传验证格式及大小
*/
function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传JPG或PNG文件!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小需小于2MB!");
    return false;
  }
  return isJpgOrPng && isLt2M;
}

const props = {
  customRequest: customRequest,
  showUploadList: false, // 不展示文件列表
  beforeUpload: beforeUpload
};

ReactDOM.render(
  <Upload {...props}>
    <Button>
      <Icon type="upload" /> Click to Upload
    </Button>
  </Upload>,
  document.getElementById("container")
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

codesandbox 示例:https://codesandbox.io/s/great-silence-lzdwm?file=/index.js

可在log中查看结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/339188?site
推荐阅读
相关标签
  

闽ICP备14008679号