1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > react使用阿里云对象存储 ali-oss antd upload to ali-oss

react使用阿里云对象存储 ali-oss antd upload to ali-oss

时间:2024-02-02 15:35:19

相关推荐

react使用阿里云对象存储 ali-oss  antd upload to ali-oss

最近写阿里云图片上传,碰到一些小问题,在此总结一下.

项目环境:

create-react-appantdnode6.1.0

看了阿里云oss对象存储sdk

直接采用node的安装方式.

在使用的时候碰到了问题.

yield client.put('file', file.url);=> TypeError: fs.createReadStream is not a function

看文档要求,换成分片上传,也会存在问题.

yield client.multipartUpload('file', file.url);=>TypeError: fs.stat is not a function

问题就是这样,node的库不在.

没有办法,尝试浏览器上传. 是可以的.

浏览器安装

index.html引入包.

<script src="/aliyun-oss-sdk.min.js"></script>

可以看快速开始.浏览器方式快速开始.

其实这里说的主要是antd库的Upload集成ali-oss上传.

import React from 'react'import {Upload, Modal} from 'antd'class Example extends ponent{state = {preview: "",visible: false,imageList: [],token: {}}render() {const props = {onRemove: (file) => {this.setState(({ imageList }) => {const index = imageList.indexOf(file);const newFileList = imageList.slice();newFileList.splice(index, 1);return {imageList: newFileList};});},beforeUpload: this.beforeUpload,fileList: this.state.imageList,onPreview: this.handlePreview,accept: "image/*",listType: "picture-card"};const {preview, visible, imageList} = this.statereturn(<div><Upload {...props}>{imageList.length >= 1 ? null : uploadButton}</Upload><Modal visible={visible} footer={null} onCancel={this.handleCancel}><img alt="example" style={{ width: '100%' }} src={preview} /></Modal></div>)}//因为我们需要与表单一起上传,所以默认是不去上传到后台服务器.beforeUpload = file => {let reader = new FileReader();reader.readAsDataURL(file);reader.onloadend = () => {UploadToOss(this, DRIVER_LICENSE_PATH, file).then(data => {this.setState(({ imageList }) => ({imageList: [{uid: file.uid,name: file.name,status: file.status,type: file.type,result: data.name,url: reader.result}],}));})}return false;}handlePreview = (file) => {this.setState({preview: file.url || file.thumbUrl,visible: true,});}componentDidMount(){//使用的sts,向后台服务器请求获取token.// setState({token: "you get result"})}}const client = (self) => {const {token} = self.statereturn new window.OSS.Wrapper({accessKeyId: token.access_key_id,accessKeySecret: token.access_key_secret,stsToken: token.security_token,region: OSS_ENDPOINT, //常量,你可以自己定义bucket: OSS_BUCKET,});}const uploadPath = (path, file) => {return `${path}/${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)})})}

上面就是uploadali-oss一起使用的列子.

原文链接

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。