1. 程式人生 > >react使用阿里雲物件儲存,ali-oss, antd upload to ali-oss

react使用阿里雲物件儲存,ali-oss, antd upload to ali-oss

最近寫阿里雲圖片上傳,碰到一些小問題,在此總結一下.
專案環境:
create-react-app antd node6.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="http://gosspublic.alicdn.com/aliyun-oss-sdk.min.js"></script>

可以看快速開始.瀏覽器方式快速開始.

其實這裡說的主要是antd 庫的 Upload 整合ali-oss 上傳.

import React from 'react'
import {Upload, Modal} from 'antd'
class Example extends React.Component{ 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.state return( <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.state return 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 一起使用的列子.