React+七牛云SDK 还有安卓不支持input的multi
2020-12-02 本文已影响0人
G_console
引入七牛云sdk npm install qiniu-js
或者cnpm
、yarn
需要后台写个接口,给你返回token
、key
import * as qiniu from 'qiniu-js'
import apiClient from 'modules/apiClient';
export async function qiniuUploader(file) {
return new Promise(async(resolve, reject) => {
const { body } = await apiClient.base.file() //这是后台给我返回的token、key
let token = body.token
let key = body.key
let pathArr=file.type.split("/")
let pathLast=pathArr[pathArr.length-1]
const observable = qiniu.upload(file, key+'.'+pathLast, token, {}, {
/** 忽略这部分注释 **/
// region: 'z0',
// domain: 'https://×××.×××.com/', // // bucket 域名,下载资源时用到。如果设置,会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
// 以下方法三选一即可,优先级为:uptoken > uptokenURL > uptokenFunc
// uptoken: token, // 由其他程序生成七牛 uptoken
// uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken,返回的格式必须是 json 且包含 uptoken 字段,例如: {"uptoken": "[yourTokenString]"}
// uptokenFunc: function() {return '[yourTokenString]';}
/** 忽略这部分注释 **/
})
observable.subscribe({
next(res){
// console.log('next', res)
},
error(err){
// console.log('err', err)
reject('')
},
complete(res){
// console.log('res', res)
resolve('https://×××.×××.com/'+res.key)
}
})
})
}
//封装组件
import Base, { Config } from 'components/Base';
import React from 'react';
import styles from './index.module.scss';
interface Props {
onChange?: (e) => void;
max?: number
type?: 'video'
}
interface State {
}
export default class Uploader extends Base<any, State> {
public state: State = {
};
private handleFileChange = async(e) => {
const { max } = this.props
e.persist()
if(!e.target){
return;
}
let file = e.target.files
let result:any[] = []
for( let i=0; i<file.length; i++ ){
if(result.length < max){
const path = await this.interface.qiniuUploader(file[i]) //就是上面封装的方法
result.push(path)
}
}
if(this.props.onChange){
this.props.onChange(result)
}
}
public render() {
const { className, type } = this.props;
const accept = type == 'video'? 'video/*': 'image/*'
return (
<div className={cx(styles.tab, className)}>
<div className={styles.box}>
<input type="file" onChange={this.handleFileChange} multiple accept={accept}/>
</div>
</div>
)
}
}
但是还有个问题,input
的multiple
在安卓大多数浏览器中不支持多选。
看这里,有一些迂回解决方案: 手机浏览器使用HTML5 input的multiple属性不能多选?