在使用antd的時(shí)候可以很方便的實(shí)現(xiàn)上傳圖片的功能啤覆,但是最近使用到阿里云的oss服務(wù)器存儲(chǔ)文件數(shù)據(jù)山孔,比較坑爹的事情就來(lái)了狞贱。雖然阿里云的官網(wǎng)文檔描述的非常詳細(xì)澈缺,但是感覺(jué)太詳細(xì)了導(dǎo)致很難找到重點(diǎn)草戈,一個(gè)上傳圖片的功能折騰了好久(可能自己比較菜吧)塌鸯。
使用dva初始化一個(gè)空白的項(xiàng)目,安裝antd插件唐片。
dva new upload-app
cd upload-app
npm i antd
引入antd的樣式文件
// index.js中
import 'antd/dist/antd.css';
首先上傳圖片建議使用網(wǎng)上的幾個(gè)npm包ali-oss丙猬,安裝方式如下
npm i ali-oss # oss功能封裝
npm i moment # 為每一天的上傳文件創(chuàng)建目錄
為了省事直接在dva框架中的Example組件中實(shí)現(xiàn)效果。
// components/Example.js
import React from 'react'
import { Upload, Icon, message } from 'antd';
import oss from 'ali-oss';
import moment from 'moment';
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
const client = (self) => {
const {token} = self.state
console.log(token);
// 當(dāng)時(shí)使用的插件版本為5.2
/*
return new oss.Wrapper({
accessKeyId: token.access_key_id,
accessKeySecret: token.access_key_secret,
region: '', //
bucket: '',//
});
*/
// 2018-12-29更新
// ali-oss v6.x版本的寫法
return new oss({
accessKeyId: token.access_key_id,
accessKeySecret: token.access_key_secret,
region: '', //
bucket: '',//
});
}
const uploadPath = (path, file) => {
// 上傳文件的路徑费韭,使用日期命名文件目錄
return `${moment().format('YYYYMMDD')}/${file.name.split(".")[0]}-${file.uid}.${file.type.split("/")[1]}`
}
const UploadToOss = (self, path, file) => {
const url = uploadPath(path, file)
return new Promise((resolve, reject) => {
client(self).multipartUpload(url, file).then(data => {
resolve(data);
}).catch(error => {
reject(error)
})
})
}
class Example extends React.Component {
state = {
loading: false,
token: {
access_key_id: '', // oss的key_id
access_key_secret: '', // oss的secret
OSS_ENDPOINT: '', // 自己oss服務(wù)器的配置信息
OSS_BUCKET: '', // 自己oss服務(wù)器的配置信息
}
};
handleChange = (info) => {
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
getBase64(info.file.originFileObj, imageUrl => this.setState({
imageUrl,
loading: false,
}));
}
}
beforeUpload = (file) => {
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
// 使用ossupload覆蓋默認(rèn)的上傳方法
UploadToOss(this, '上傳路徑oss配置信息', file).then(data => {
console.log(data.res.requestUrls)
this.setState({ imageUrl: data.res.requestUrls });
})
}
return false; // 不調(diào)用默認(rèn)的上傳方法
}
render() {
const uploadButton = (
<div>
<Icon type={this.state.loading ? 'loading' : 'plus'} />
<div className="ant-upload-text">Upload</div>
</div>
);
const imageUrl = this.state.imageUrl;
return (
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
beforeUpload={this.beforeUpload}
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="" /> : uploadButton}
</Upload>
);
}
}
export default Example;