使用js上传图片到阿里云

16 篇文章 1 订阅

1.在index.html文件中引入阿里云sdk

 <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>

引入后console.log(window)如下,会发现有一个OSS方法
在这里插入图片描述
2.app.js或者router.js里引入

let OSS = window.OSS.Wrapper
let client = new OSS({
	 region: 'oss-cn-hangzhou'       //这里填写你的oss地址
   accessKeyId: ‘这里填写你的ak‘,
    accessKeySecret: ‘这里填写你的aks‘,
    secure: true,
    bucket: ‘这里填写你的oss名
});
window.client = client

3.封装上传方法 upload.js

class Http {
	 uploadFile (file,val) {
	    let suffix = val.substr(val.indexOf("."));
	    let storeAs = "file/" + new Date() * 1 + suffix;
	    return client.multipartUpload(storeAs, file).then(result=>{
	        let obj = {}
	        obj.key=result.name
	        obj.url=client.signatureUrl(result.name)
	       return Promise.resolve(obj)
	    })
	  }
  }
   export default new Http()

4.在antd Upload组件上封装upload图片上传组件

import React,{ Component } from 'react'
import { Upload, Modal, message } from 'antd';
import http from '../upload.js';
import './index.less'
function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
class UploadCmpextends Component{
  static getDerivedStateFromProps(nextProps, prevState,) {
    const {prevPropValue} = prevState
    let { value } = nextProps
    if(JSON.stringify(value) !== JSON.stringify(prevPropValue)){
      return {
        fileList: value,
        prevPropValue: value,
      }
    }
    return null;
  }
  constructor(props) {
    super(props);
    this.state = {
        previewVisible: false,
        previewImage: '',
        prevPropValue:[],
        fileList: [],
    };
  }
  handleCancel = () => this.setState({ previewVisible: false });
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList }) => {
    if(fileList.length==0){
      this.setState({ fileList })
      this.triggerChange(fileList);
    }
  };
  triggerChange = changedValue => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(
        changedValue,
      );
    }
  };

  beforeUpload = (file) => {
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      return message.error('图片不能超过5M!');
    }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      // 使用ossupload覆盖默认的上传方法
      http.uploadFile(file,file.name).then((data) => {
        let fileList = [{url:data.url,uid:data.key,name:data.key}]
        this.setState({ fileList})
        this.triggerChange(fileList);//只返回id
      })
    }
    return false; // 不调用默认的上传方法
  }
  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
        <img src={require("../../assets/image/upload.png")} alt="" className="uploadImg"/>
    );
    return (
      <div className="clearfix">
        <Upload
          name="file"
          accept="image/png, image/jpeg, image/jpg"
          listType="picture-card"
          className="avatar-uploader"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          beforeUpload={this.beforeUpload}
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default UploadCmp

5.使用组件

 <Form.Item label="广告图:" extra="广告尺寸300*750,支持JPG、PNG、JPEG 上传">
              {getFieldDecorator('logo', {
                initialValue: rowData&&rowData.logo!=""?[{url:rowData.logoUrl,uid:rowData.logo,name:rowData.logo}]:[],
              })(
                <UploadImg />
              )}
            </Form.Item>

6.效果如图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值