使用PHP服务器上传本机图像

时间:2019-11-30 16:27:55

标签: php image react-native upload

无法将图像从react-native代码上传到PHP服务器,但是使用邮递员可以毫无问题地上传图像,我想问题与服务器或后端无关,但我将提供前端后端代码 我尝试了其他库,例如react-native-document-picker和react-native-image-crop-picker,但是没有希望,所以请您告诉我问题出在哪里

PHP代码

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
        );

    }

本机代码

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

2 个答案:

答案 0 :(得分:0)

我想我发现问题是逐步解决的,它可能会解决:

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

最重要的是安装表单数据包来解决此问题 在那之前,请与邮递员一起测试您的后端,以确保其正常工作,并且问题仅与前者有关,然后按照以下步骤操作,我希望您对其进行修复。

答案 1 :(得分:0)

我明白了,服务器只是在等待附件

        if ($request->attachments != null) 

当我发送my_photo时

            data.append('my_photo', 

仅将my_photo更改为附件即可解决我的问题