当前位置:网站首页>Uploading pictures on Alibaba cloud OSS
Uploading pictures on Alibaba cloud OSS
2022-07-26 08:54:00 【Arrogance.miner】
Installation dependency npm install --save axios js-base64
Click the Modify button
Pop up a box to select a picture or file
Code
index.js
<AliyunOSSUpload onGetFileUrl={onGetFileUrl} />
AliyunOSSUpload.js
import React from 'react';
import { Form, Upload, message, Button } from 'antd';
import { getOSSClientCredit, policyUpload } from '@/services/login';
import { Base64 } from 'js-base64';
import hmacSHA1 from 'crypto-js/hmac-sha1';
import CryptoBase64 from 'crypto-js/enc-base64';
export class AliyunOSSUpload extends React.Component {
constructor() {
super();
this.state = {
OSSData: {},
setDataObj: {},
loading: false,
};
this.dataObj = {};
}
getPolicyBase64 = (expiration) => {
const policyText = {
expiration: expiration, // Set the Policy The expiration time of , After this expiration time , There's no way to get through this policy Uploaded the file
conditions: [
['content-length-range', 0, 10 * 1024 * 1024], // Set the size limit of the uploaded file ,5mb
],
};
const policyBase64 = Base64.encode(JSON.stringify(policyText));
return policyBase64;
};
getSignature = (policyBase64, keySecret) => {
const signature = CryptoBase64.stringify(hmacSHA1(policyBase64, keySecret));
return signature;
};
onChange = ({ fileList }) => {
const { onChange } = this.props;
console.log('Aliyun OSS:', fileList);
this.setState({ fileList: fileList }, async () => {});
if (fileList[0].status !== 'uploading') {
}
if (fileList[0].status === 'done') {
message.success(`file uploaded successfully`);
} else if (fileList[0].status === 'error') {
message.error(`file upload failed.`);
}
if (onChange) {
onChange([...fileList]);
}
};
onRemove = (file) => {
const { value, onChange } = this.props;
const files = value.filter((v) => v.url !== file.url);
if (onChange) {
onChange(files);
}
};
beforeUpload = async (file) => {
this.setState({
loading: true,
});
let _self = this;
return new Promise((resolve, reject) => {
console.log(' file name :', file);
getOSSClientCredit().then((res) => {
// An interface given by the backend obtain key Values, etc. need to be submitted to Alibaba cloud
const policyBase64 = this.getPolicyBase64(res.data.expiration);
const signature = this.getSignature(policyBase64, res.data.accessKeySecret); // Get a signature
_self.dataObj.key = `${res.data.basePath}/${file.name}`;
_self.dataObj.basePath = res.data.basePath;
// eslint-disable-next-line no-template-curly-in-string
_self.dataObj.OSSAccessKeyId = res.data.accessKeyId;
_self.dataObj.success_action_status = '200';
_self.dataObj.bucket = res.data.bucket;
_self.dataObj['x-oss-security-token'] = res.data.securityToken;
_self.dataObj.policy = policyBase64;
_self.dataObj.signature = signature;
console.log(' Response data ...', _self.dataObj);
this.setState({ setDataObj: _self.dataObj });
resolve(true);
});
});
return file;
};
render() {
console.log(this.state.OSSData);
const { value } = this.props;
const props = {
name: 'file',
fileList: this.state.fileList,
// Alibaba cloud
action: `https://${this.state?.setDataObj?.bucket}.oss-cn-hangzhou.aliyuncs.com/`,
onChange: this.onChange,
onRemove: this.onRemove,
// Data submitted
data: this.dataObj,
beforeUpload: this.beforeUpload,
onSuccess: (res, file) => {
this.setState({
loading: false,
});
console.log('onSuccess', res, file.name);
console.log(this.state?.setDataObj);
const url = `https://${this.state?.setDataObj?.bucket}.oss-cn-hangzhou.aliyuncs.com/${this.state?.setDataObj?.key}`;
this.props.onGetFileUrl && this.props.onGetFileUrl(url);
},
};
return (
<Upload {...props}>
<Button loading={this.state.loading}> modify </Button>
</Upload>
);
}
}
getOSSClientCredit The data returned by the interface
oss-cn-hangzhou.aliyuncs.com/ Data submitted
The return value is empty At this time, cross domain Need to be in OSS Management console settings cross domain I was looking for this leader To configure the He should have an account and password to
When the request succeeds stay onSuccess
Method to obtain and splice the uploaded address https://${this.state?.setDataObj?.bucket}.oss-cn-hangzhou.aliyuncs.com/${this.state?.setDataObj?.key}
Modification successful
边栏推荐
- 【数据库 】GBase 8a MPP Cluster V95 安装和卸载
- MySQL 8.0 OCP 1z0-908 certification examination question bank 1
- 03异常处理,状态保持,请求钩子---04大型项目结构与蓝图
- [search topics] flood coverage of search questions after reading the inevitable meeting
- 有限元学习知识点备案
- Oracle 19C OCP 1z0-082 certification examination question bank (7-12)
- Day06 homework - skill question 6
- Excel find duplicate lines
- Oracle 19C OCP 1z0-083 question bank (7-12)
- [freeswitch development practice] use SIP client Yate to connect freeswitch for VoIP calls
猜你喜欢
随机推荐
数据库操作技能7
Uni app simple mall production
Huffman transformation software based on C language
Pan micro e-cology8 foreground SQL injection POC
数据库操作 技能6
Oracle 19C OCP 1z0-082 certification examination question bank (24-29)
Foundry教程:使用多种方式编写可升级的智能合约(上)
node-v下载与应用、ES6模块导入与导出
12306 ticket system crawling - 1. Saving and reading of city code data
KV database based on raft consensus protocol
Cve-2021-21975 VMware SSRF vulnerability recurrence
day06 作业---技能题7
Typescript encryption tool passwordencoder
Ansible important components (playbook)
Xtrabackup appears' flush no '_ WRITE_ TO_ BINLOG TABLES‘: 1205 (HY000) Lock wait timeout exceeded;
Day06 homework - skill question 6
Recurrence of SQL injection vulnerability in the foreground of a 60 terminal security management system
The idea shortcut key ALT realizes the whole column operation
数据库操作 题目二
Set of pl/sql