当前位置:网站首页>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 
边栏推荐
- Analysis on the query method and efficiency of Oracle about date type
- 合工大苍穹战队视觉组培训Day6——传统视觉,图像处理
- Self review ideas of probability theory
- Day06 homework - skill question 6
- General file upload vulnerability getshell of a digital campus system (penetration test -0day)
- Cve-2021-21975 VMware SSRF vulnerability recurrence
- JS file import of node
- Store a group of positive and negative numbers respectively, and count the number of 0 -- assembly language implementation
- Oracle 19C OCP 1z0-082 certification examination question bank (19-23)
- Arbitrum Nova release! Create a low-cost and high-speed dedicated chain in the game social field
猜你喜欢

Memory management based on C language - Simulation of dynamic partition allocation

Super potential public chain dfinity -- the best time for DFI developers to enter

Media at home and abroad publicize that we should strictly grasp the content

数据库操作 题目一

Regular expression: judge whether it conforms to USD format

Cadence(十)走线技巧与注意事项

第6天总结&数据库作业

sklearn 机器学习基础(线性回归、欠拟合、过拟合、岭回归、模型加载保存)

解决C#跨线程调用窗体控件的问题

day06 作业---技能题7
随机推荐
What are the differences in the performance of different usages such as count (*), count (primary key ID), count (field) and count (1)? That's more efficient
Replication of SQL injection vulnerability in the foreground of Pan micro e-cology8
Database operation skills 7
IC's first global hacking bonus is up to US $6million, helping developers venture into web 3!
[search topics] flood coverage of search questions after reading the inevitable meeting
Oracle 19C OCP 1z0-083 question bank (1-6)
One click deployment of lamp and LNMP scripts is worth having
Xshell batch send command to multiple sessions
Kotlin properties and fields
P1825 [USACO11OPEN]Corn Maze S
【FreeSwitch开发实践】自定义模块创建与使用
Day06 homework - skill question 6
第6天总结&数据库作业
Study notes of automatic control principle --- stability analysis of control system
Cve-2021-3156 duplicate of sudo heap overflow privilege raising vulnerability
keepalived双机热备
at、crontab
Foundry教程:使用多种方式编写可升级的智能合约(上)
Leetcode and query question summary
Spark SQL common date functions