美文网首页
react 图片上传功能实现(附核心代码)

react 图片上传功能实现(附核心代码)

作者: CoderZb | 来源:发表于2020-08-08 10:17 被阅读0次

    react 图片上传的核心注意点有4个吧。
    1.将input标签设置为type="file"
    2.选择图片后要知道使用e.target.files[0]将图片内容取出来。
    3.创建new FormData()的对象,并构造后天所需要的参数。
    4.axios请求时,请求头类型为{'Content-Type': 'multipart/form-data'}

    • 上传前


      image.png
    • 上传后


      image.png
    • 接口参数,注意有个参数的是(binary)
      image.png

    核心代码

    import React, { PureComponent } from "react";
    import {Button} from "antd";
    import axios from "axios";
    const { Fragment } = React;
    const saveStoreZeroCharge =
      global.constants.website + "/feiyangshop-admin-react/saveStoreZeroCharge";
    class Operation extends React.PureComponent {
      constructor(props) {
        super(props);
        this.state = {
          file:'',
          showImg:'none',
          token:'jianshu',
          name:'CoderZb',
          
    storeId:'91',
          subsidyAmount:'82',
          imagePreviewUrl:'',
        }
      }
      render() {
        var {imagePreviewUrl,showImg} = this.state;
        var imagePreview = null;
        if (imagePreviewUrl) {
          imagePreview = ( <label  for="avatarFor">< img style={{width:'80px',height:'80px'}} src={imagePreviewUrl} /></label>);
          showImg = 'none';
        } else {
          showImg = 'block';
        }
    
        return (
          <Fragment>
              <p style={{ margin: "0" }}>上传打款凭证:</p>
                <input id="avatarFor" style={{display:'none'}} type="file" onChange={(e)=>this.handleImageChange(e)}/>
                {imagePreview}
                <label style={{color:"#1890FF",border:"1px dashed #1890FF",padding:'3px 10px ',display:showImg}} for="avatarFor">+点击上传图片</label>
               
                <Button
                  key="submit"
                  type="primary"
                  onClick={this.chargeFunc}
                >
                  确定{" "}
                </Button>
          </Fragment>
        );
      }
    
      
     handleImageChange(e) {
        e.preventDefault();
        
        var reader = new FileReader();
        var file = e.target.files[0];
        
        reader.onloadend = () => {
          console.log('文件名为—',file);
          console.log('文件结果为—',reader.result);
          this.setState({
          file: file,
          imagePreviewUrl: reader.result
          });
        }
        
        reader.readAsDataURL(file)
      }
      chargeFunc= (e) => { 
        console.log("file为",this.state.file);
          const formData = new FormData();
          console.log("one------");
          // formData.append('file',value);
          formData.append('filename', this.state.file)
          formData.append('token',this.state.token);
          formData.append('userName',this.state.name);
          formData.append('storeId',this.state.storeId);
          formData.append('chargeMoney',this.state.subsidyAmount);
          let config = {
            method: 'post',
            headers:{'Content-Type': 'multipart/form-data'}
          }
          axios.post(saveStoreZeroCharge,formData,config).then((res) => {
            if (res.data.msg == '用户登陆已过期') {
                alert("请重新登录");
                return false;
            }
            if (res.data.status === 200) {
    
                // this.getStoreInfo();
            }
            if (res.data.status != 200) {
    
                return false;
            }
        }).catch((error) => {
            console.log(error);
        })
      }
    }
    
    export default Operation;
    

    相关文章

      网友评论

          本文标题:react 图片上传功能实现(附核心代码)

          本文链接:https://www.haomeiwen.com/subject/mazfdktx.html