当前位置:网站首页>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 
边栏推荐
- File management file system based on C #
- Registration of finite element learning knowledge points
- [freeswitch development practice] user defined module creation and use
- day06 作业--技能题6
- My meeting of OA project (query)
- MySQL 8.0 OCP 1z0-908 certification examination question bank 1
- Study notes of automatic control principle -- dynamic model of feedback control system
- 12306 ticket system crawling - 1. Saving and reading of city code data
- Kotlin属性与字段
- Leetcode and query question summary
猜你喜欢
随机推荐
解决C#跨线程调用窗体控件的问题
Oracle 19C OCP 1z0-082 certification examination question bank (19-23)
Recurrence of SQL injection vulnerability in the foreground of a 60 terminal security management system
6、 Pinda general permission system__ pd-tools-log
node-v下载与应用、ES6模块导入与导出
Web3 Games: current situation and future
Database operation topic 1
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
合工大苍穹战队视觉组培训Day5——机器学习,图像识别项目
P3743 kotori的设备
pl/sql之动态sql与异常
Memory management - dynamic partition allocation simulation
OA项目之我的会议(会议排座&送审)
Pan micro e-cology8 foreground SQL injection POC
12306 ticket system crawling - 1. Saving and reading of city code data
The lessons of 2000. Web3 = the third industrial revolution?
有限元学习知识点备案
Huffman transformation software based on C language
Excel find duplicate lines
Overview of motion recognition evaluation








![[untitled]](/img/3e/fb7c4d901643e6ea88a7d90ead045c.png)
