在ES6中识别不同的文件类型

时间:2018-03-24 02:39:04

标签: javascript react-native

我有这行代码

formData.append('picture', {uri: this.state.avatarSource.uri, name: 'photo.png', type: 'image/png'});

但我想"支持"许多格式。我的后端代码可以自动处理格式"#34;并且可以确定它是否是视频:

for upload in self.get_uploads():
    try:
        content_type = blobstore.blobstore.BlobInfo(upload.key()).content_type
        if 'video' in content_type:

现在我不需要立即支持视频,但我想以一般方式处理图像格式。它在脚本中看起来我只能支持png图像。

客户端代码的其余部分:

import React, {Component} from 'react';
import {Alert, AsyncStorage, Dimensions, Image, Picker, PixelRatio, ScrollView, TouchableOpacity, StyleSheet, Text, TextInput, View} from 'react-native';
import {Button, Input} from 'react-native-elements'

import Icon from 'react-native-vector-icons/FontAwesome';
import ImagePicker from 'react-native-image-picker';
const SCREEN_WIDTH = Dimensions.get('window').width;
options = {
    title: 'Select Avatar',
    customButtons: [
        {name: 'fb', title: 'Choose Photo from Facebook'},
    ],
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};
const formData = new FormData();
class Buttons extends Component {

    constructor(props) {
        super(props);


        if (AsyncStorage.getItem('name')) {
            name = AsyncStorage.getItem('name');
        }


        if (AsyncStorage.getItem('auth_id')) {
            auth_id = AsyncStorage.getItem('auth_id');
        }


        this.state = {avatarSource: null,
            videoSource: null,
            name: name,
            auth_id: auth_id,
            upload_url: '',
            country: '',
            category: '',
            region: '',
            city: '',
            title: '',
            text: '',
            options: {
                "4699201": "Kumbakonam",
                "4699202": "Madurai",
                "4700196": "Chengalpattu",
                "4700197": "Coonoor",
                "4693193": "Tiruchirappalli",
                "4700198": "Kanchipuram",
                "4700199": "Pudukkottai",
                "4703196": "Thoothukkudi",
                "4701199": "Karur",
                "4691203": "Avadi",
                "4691202": "Ambattur",
                "4697199": "Thanjavur",
                "4697198": "Chennai",
                "4691205": "Other city",
                "4696196": "Salem",
                "4691204": "Vellore",
                "4701198": "Erode",
                "4701200": "Tiruvannamalai",
                "4694193": "Arakonam",
                "4692202": "Hosur",
                "4692203": "Pollachi",
                "4702196": "Dindigul",
                "4702197": "Tambaram",
                "4695201": "Cuddalore",
                "4695202": "Tiruppur",
                "4704192": "Coimbatore",
                "4702198": "Tirunelveli",
                "4676202": "Namakkal",
                "4676201": "Nagercoil"
            }
        };
    }

    selectPhotoTapped() {
        const options = {
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true
            }
        };

        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled photo picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                let source = { uri: response.uri };

                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };

                this.setState({
                    avatarSource: source
                });
            }
        });
    }

    selectVideoTapped() {
        const options = {
            title: 'Video Picker',
            takePhotoButtonTitle: 'Take Video...',
            mediaType: 'video',
            videoQuality: 'medium'
        };

        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled video picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                this.setState({
                    videoSource: response.uri
                });
            }
        });
    }
    selectCountry(val) {
        this.setState({country: val});
    }

    setTitle(val) {
        this.setState({title: val});
    }

    setCategory(val) {
        this.setState({category: val});
    }

    setCity(val) {
        this.setState({city: val});
    }

    setText(val) {
        this.setState({text: val});
    }

    selectRegion(val) {
        this.setState({region: val});
        fetch('https://www.koolbusiness.com/cities/insert/api', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                "region_id": val,
            }),
        }).then((response) => response.json())
            .then((responseJson) => {
                this.setCities(responseJson);
            })
            .catch((error) => {
                console.error(error);
            });
    }

    setCities = (value) => {
        this.setState({'options': value});
    };
    setName = (value) => {
        this.setState({'name': value});
    };

    onPressLearnMore = () => {
        AsyncStorage.getItem("auth_id").then((value) => {

            formData.append('auth_id', value);
            formData.append('title', this.state.title);
            formData.append('text', this.state.text);
            formData.append('city', this.state.city);
            formData.append('category', this.state.category);
            formData.append('picture', {uri: this.state.avatarSource.uri, name: 'photo.png', type: 'image/png'});
            fetch(this.state.upload_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                body: formData,

            }).then((response) => response.json())
                .then((responseJson) => {
                    Alert.alert(
                        'Thank you ' + this.state.name,
                        'Your ad was posted',
                        [

                            {text: 'OK', onPress: () => console.log('OK Pressed')},
                            {text: 'Logout', onPress: () => AsyncStorage.clear()},
                        ],
                        {cancelable: false}
                    );
                })
                .catch((error) => {
                    console.error(error);
                    Alert.alert(
                        'An error has occurred',
                        [
                            {text: 'OK', onPress: () => console.log('OK Pressed')},
                            {text: 'Logout', onPress: () => AsyncStorage.clear()},
                        ],
                        {cancelable: false}
                    );
                });




        });


    };

    componentDidMount() {

        AsyncStorage.getItem("name").then((value) => {

            this.state.name = value;

        });

        fetch('https://www.koolbusiness.com/cities/insert/api', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                "region_id": "4701188",
                "password": this.state.password,
            }),
        }).then((response) => response.json())
            .then((responseJson) => {
                this.setCities(responseJson);
            })
            .catch((error) => {
                console.error(error);
            });

        fetch('https://www.koolbusiness.com/api/getuploadurl', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        }).then((response) => response.json())
            .then((responseJson) => {
                //this.setState(upload_url=responseJson);
                //let t = responseJson;
                //obj = JSON.parse(responseJson);
               // this.setState(upload_url, responseJson["upload_url"])
                this.setState({'upload_url': responseJson.upload_url});

            })
            .catch((error) => {
                console.error(error);
            });

    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <View style={styles.contentView}>
                    <View style={styles.headerContainer}>
                        <Icon color="white" name="rocket" size={62}/>
                        <Text style={styles.heading}>Create your ad</Text>
                    </View>

                    <Text>Pick a Category</Text>
                    <Picker selectedValue={this.state.category}
                            onValueChange={(itemValue, itemIndex) => this.setCategory(itemValue)}
                    >


                        <Picker.Item label="Houses" value="1020"/>
                        <Picker.Item label="Apartments" value="1010"/>
                        <Picker.Item label="Vacation homes" value="1030"/>
                        <Picker.Item label="Offices" value="1050"/>
                        <Picker.Item label="Land" value="1080"/>
                        <Picker.Item label="Flatmates/Paying Guest" value="1100"/>


                        <Picker.Item label="Cars" value="2010"/>
                        <Picker.Item label="Motorcycles" value="2030"/>
                        <Picker.Item label="Accessories &amp; parts" value="2040"/>
                        <Picker.Item label="Trucks" value="2080"/>
                        <Picker.Item label="Other vehicles" value="2070"/>
                        <Picker.Item label="Home &amp; Personal items" value="js"/>
                        <Picker.Item label="Home &amp; Garden" value="3040"/>
                        <Picker.Item label="Clothing" value="3050"/>
                        <Picker.Item label="For Kids (Toys &amp; Clothes)" value="3030"/>
                        <Picker.Item label="Jewelry &amp; Watches" value="3060"/>
                        <Picker.Item label="Leisure, Sports &amp; hobby" value="js"/>
                        <Picker.Item label="Hobbies" value="4010"/>
                        <Picker.Item label="Sports &amp; Bicycles" value="4020"/>
                        <Picker.Item label="Movies, Books &amp; Magazines" value="4040"/>
                        <Picker.Item label="Pets" value="4030"/>
                        <Picker.Item label="Tickets" value="4090"/>
                        <Picker.Item label="Art &amp; Collectibles" value="4060"/>
                        <Picker.Item label="Music &amp; Instruments" value="4070"/>

                        <Picker.Item label="Computers &amp; Accessories" value="5030"/>
                        <Picker.Item label="TV, Audio, Video, Cameras" value="5020"/>
                        <Picker.Item label="Cellphones &amp; gadgets" value="5010"/>
                        <Picker.Item label="Video games &amp; consoles" value="5040"/>
                        <Picker.Item label="Jobs &amp; Services" value="js"/>
                        <Picker.Item label="Job offers" value="6010"/>
                        <Picker.Item label="Resumes" value="6020"/>
                        <Picker.Item label="Services" value="6030"/>
                        <Picker.Item label="Classes" value="6040"/>
                        <Picker.Item label="Professional/Office equipment" value="6090"/>

                        <Picker.Item label="Other" value="7010"/>
                    </Picker>
                    <Text>Pick a Region</Text>

                    <Picker selectedValue={this.state.region}
                            onValueChange={(itemValue, itemIndex) => this.selectRegion(itemValue)}
                    >

                        <Picker.Item label="Andaman &amp; Nicobar Islands" value="4703187"/>
                        <Picker.Item label="Andhra Pradesh" value="4694186"/>
                        <Picker.Item label="Arunachal Pradesh" value="4699188"/>
                        <Picker.Item label="Assam" value="4692186"/>
                        <Picker.Item label="Bihar" value="4702186"/>
                        <Picker.Item label="Chandigarh" value="4698185"/>
                        <Picker.Item label="Chhattisgarh" value="4676188"/>
                        <Picker.Item label="Dadra &amp; Nagar Haveli" value="4691190"/>
                        <Picker.Item label="Daman &amp; Diu" value="4704183"/>
                        <Picker.Item label="Delhi" value="4699183"/>
                        <Picker.Item label="Goa" value="4702187"/>
                        <Picker.Item label="Gujarat" value="4691189"/>
                        <Picker.Item label="Haryana" value="4700186"/>
                        <Picker.Item label="Himachal Pradesh" value="4703185"/>
                        <Picker.Item label="Jammu &amp; Kashmir" value="4694187"/>
                        <Picker.Item label="Jharkhand" value="4699189"/>
                        <Picker.Item label="Karnataka" value="4701185"/>
                        <Picker.Item label="Kerala" value="4695189"/>
                        <Picker.Item label="Lakshadweep" value="4700189"/>
                        <Picker.Item label="Madhya Pradesh" value="4697186"/>
                        <Picker.Item label="Maharashtra" value="4694184"/>
                        <Picker.Item label="Manipur" value="4700187"/>
                        <Picker.Item label="Meghalaya" value="4703186"/>
                        <Picker.Item label="Mizoram" value="4698184"/>
                        <Picker.Item label="Nagaland" value="4692187"/>
                        <Picker.Item label="Orissa" value="4696185"/>
                        <Picker.Item label="Pondicherry" value="4676189"/>
                        <Picker.Item label="Punjab" value="4693185"/>
                        <Picker.Item label="Rajasthan" value="4701186"/>
                        <Picker.Item label="Sikkim" value="4701187"/>


                        <Picker.Item label="Tamil Nadu" value="4701188"/>

                        <Picker.Item label="Telangana" value="4984687332163584"/>
                        <Picker.Item label="Tripura" value="4697187"/>
                        <Picker.Item label="Uttaranchal" value="4699190"/>
                        <Picker.Item label="Uttar Pradesh" value="4692188"/>
                        <Picker.Item label="West Bengal" value="4700188"/>
                    </Picker>
                    <Text>Pick a City</Text>

                    <Picker selectedValue={this.state.city}
                            onValueChange={(itemValue, itemIndex) => this.setCity(itemValue)}
                    >
                        {Object.keys(this.state.options).map((key) => {
                            return (<Picker.Item label={this.state.options[key]} value={key} key={key}/>) //if you have a bunch of keys value pair
                        })}
                    </Picker>

                    <Input

                           keyboardAppearance='light'
                           autoFocus={false}
                           autoCapitalize='none'
                           autoCorrect={false}
                           onChangeText={(title) => this.setState({title})}
                           value={this.state.title}
                           returnKeyType='next'
                           inputStyle={{marginLeft: 10}}

                           containerStyle={{borderBottomColor: 'rgba(0, 0, 0, 0.38)'}} placeholder="Subject" />
                    <TextInput

                        multiline={true}
                        numberOfLines = {4}
                        placeholder="Type your text here!"
                        onChangeText={(text) => this.setState({text})}
                        value={this.state.text}
                    />
                    <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
                        <View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
                            { this.state.avatarSource === null ? <Text>Select a Photo</Text> :
                                <Image style={styles.avatar} source={this.state.avatarSource} />
                            }
                        </View>
                    </TouchableOpacity>

                    <Button
                        onPress={this.onPressLearnMore}

                        title="SUBMIT"
                        disabled={false}
                        titleStyle={{fontWeight: '700'}}
                        buttonStyle={{
                            backgroundColor: 'rgba(92, 99,216, 1)',
                            width: 300,
                            height: 45,
                            borderColor: 'transparent',
                            borderWidth: 0,
                            borderRadius: 5
                        }}
                        containerStyle={{marginTop: 20}}
                    />


                </View>
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white'
    },
    contentView: {
        flex: 1
    },avatarContainer: {
        borderColor: '#9B9B9B',
        borderWidth: 1 / PixelRatio.get(),
        justifyContent: 'center',
        alignItems: 'center'
    },
    avatar: {
        borderRadius: 75,
        width: 150,
        height: 150
    },
    headerContainer: {
        justifyContent: 'center',
        alignItems: 'center',
        padding: 40,
        backgroundColor: '#4F80E1',
        marginBottom: 20
    },
    heading: {
        color: 'white',
        marginTop: 10,
        fontSize: 22,
        fontWeight: 'bold'
    },
});

export default Buttons;

1 个答案:

答案 0 :(得分:1)

不确定问题究竟是什么,但您可以使用文件选择器而不是react-native-image-picker,并在状态中设置File对象,并将其直接附加到formData,如下所示:

formData.append('picture', file);