UNPKG

elephant-com

Version:

the general component for elephant washing shoes

113 lines (102 loc) 3.2 kB
import React, { Component } from 'react'; import { View, TouchableWithoutFeedback, Text, Image, StyleSheet } from 'react-native'; import { Flex, Toast } from 'antd-mobile'; import { v4 } from 'uuid'; import PropTypes from 'prop-types'; import { ImagePickerCustom } from './ImagePickerCustom'; export default class AlbumPicker extends Component { constructor(props) { super(props); this.state = { data: props.data, }; } onStartUpload(file, i) { const { data, url } = this.getFormData(file); const formData = new FormData(); if (data) { Object.keys(data).forEach(key => formData.append(key, data[key])); } formData.append('file', { uri: file.path, type: 'image/jpg', name: 'image.jpg' }); /* eslint-disable no-undef */ fetch(this.props.sign.action, { method: 'post', headers: { 'Content-Type': 'multipart/form-data', }, body: formData, }).then(() => { this.state.data[i].url = url; this.setState({ data: this.state.data }); if (this.props.onChange) this.props.onChange(this.state.data.map(d => d.url)); }).catch((e) => { Toast.fail(e.message); }); } /* eslint-disable class-methods-use-this */ getRandomName(fileName) { const pos = fileName.lastIndexOf('.'); const suffix = pos === -1 ? '' : fileName.substring(pos); return v4().replace(/-/g, '') + suffix; } getFormData(file) { const sign = this.props.sign; const dir = sign.OssDir.endsWith('/') ? sign.OssDir : `${sign.OssDir}/`; const action = sign.action.endsWith('/') ? sign.action : `${sign.action}/`; const fileKey = `${dir}${this.getRandomName(file.filename)}`; const curFileUrl = `${action}${fileKey}`; const data = { signature: sign.OssSignature, OSSAccessKeyId: sign.OssAccessId, policy: sign.OssPolicy, key: fileKey, success_action_status: 200, }; return { data, url: curFileUrl }; } render() { /* eslint-disable react/no-array-index-key */ const fixedItems = this.state.data.map((f, i) => (<View key={`${f.url}${i}`} style={styles.imgItem}> <TouchableWithoutFeedback onPress={() => { ImagePickerCustom({ title: `选择${this.state.data[i].title}`, options: {}, callback: (file) => { this.onStartUpload(file, i); }, }); }} > <Image style={styles.img} source={{ uri: f.url }} /> </TouchableWithoutFeedback> <Text>{f.title}</Text> </View>)); if (fixedItems.length % 2) { fixedItems.push(<Text style={{ width: 150 }} />); } return (<Flex justify="around" wrap="wrap"> {fixedItems} </Flex>); } } AlbumPicker.propsTypes = { data: PropTypes.array.isRequired, sign: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, }; const styles = StyleSheet.create({ img: { borderWidth: 5, resizeMode: 'stretch', borderColor: '#ccc', width: 140, height: 140, marginBottom: 10, }, imgItem: { flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', margin: 5, marginTop: 15, }, });