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.效果如图