简体   繁体   中英

react-native image upload with PHP server

can't upload images from react-native code to PHP server, however images are uploaded without any problem using postman, i suppose the problem isn't related with the server or the back end, but I'll provide the front end and back end code I tried different libraries like react-native-document-picker and react-native-image-crop-picker but with no hope, so please could you tell me where exactly the problem is

PHP code

public function createApiImage(Request $request)
    {
        $attachment = [];
        if ($request->attachments != null) {
            $attachment = $request->attachments ;
            $photo_name = 'ads';
            $imgPath =  $attachment->store("{$photo_name}", 'public');
            $attachment1 =[
                'type' => $attachment->getMimeType(),
                'path' => $attachment->store("{$photo_name}", 'public'),
                'name' => $attachment->getClientOriginalName(),
                'created_at' => \Carbon\Carbon::now()
            ];

            $imgPathUrl = 'http://dejara.net/storage/app/public/'.$imgPath;

                $Mediadate = ['name' => "$imgPathUrl",'linked_id' => 0];
                $media = Media::create($Mediadate);
        }


        return response()->json([
            'success' => 'true',
             'info' => [
                 'Media' => $media,
             ]
            ]
            , 200
        );

    }

react-native code

import React, { Component } from 'react';
import ImagePicker from 'react-native-image-picker'
import { Text, View, TouchableOpacity, BackHandler, Image, ScrollView, Platform, ActivityIndicator, StatusBar, Dimensions } from 'react-native'
import { RFValue } from 'react-native-responsive-fontsize';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'

class PlaceAd extends Component {
    state = {
        pickedImages: []
    }

    pickImage = async () => {
        ImagePicker.showImagePicker({ title: "choose your image" }, res => {
            if (res.didCancel)
                console.log('User cancelled')
            else if (res.error)
                console.log(res.error)
            else {
                // console.log(res)

                let temp = this.state.pickedImages
                temp.push({ uri: res.uri, name: res.fileName, type: res.type, path: res.path })

                this.setState({ pickedImages: temp })
            }
        })
    }

    createAdv = () => {
        var data = new FormData();
        this.state.pickedImages.map((image, i) => {
            data.append('my_photo', {
                uri: image.uri,
                path: image.uri,
                name: image.name,
                type: image.type,
            })
        })

        fetch('http://dejara.net/public/api/createAdsImage', {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data'
            },
            method: 'POST',
            body: data
        })
            .then(response => response.json())
            .then(res => {
                console.log(res)
            })
            .catch(err => {
                console.log(err)
            })
    }

    render() {
        return (
            <View style={{width:'100%', alignItems:'center'}}>
                <TouchableOpacity style={{ marginBottom: RFValue(20), marginTop: RFValue(10), width: RFValue(150), height: RFValue(150), justifyContent: 'center', alignItems: 'center', borderWidth: 1 }} onPress={this.pickImage}>
                    <FontAwesomeIcon name="photo" size={RFValue(20)} color="#000" />
                    <Text style={{ color: "#000" }}>choose photo</Text>
                </TouchableOpacity>
                <TouchableOpacity style={[{ width: '60%', height: RFValue(50), marginBottom: RFValue(15) }]} onPress={this.createAdv} >
                    <Text>Publish</Text>
                </TouchableOpacity>

            </View>
        )
    }
}
export default PlaceAd

I guess I found the problem do step by step and it may fix :

1- npm install form-data
2- import formData from 'from-data';
3- change var to const ===>   const data = new FormData();

the most important thing is to install the form-data package to fix this issue before that test your backend with postman to make sure it works properly and the problem is just about the fronend and follow that steps and i hope you fix it.

I got it, the server just waits for attachments

        if ($request->attachments != null) 

while i send my_photo instead

            data.append('my_photo', 

just changing my_photo to attachments solved my issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM