繁体   English   中英

使用 PHP 服务器上传本地图片

[英]react-native image upload with PHP server

无法将图像从 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

我想我发现问题一步一步来,它可能会解决:

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

最重要的是安装 form-data 包来解决这个问题,然后用邮递员测试你的后端以确保它正常工作,问题只是关于前端并按照这些步骤操作,我希望你能解决它。

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

        if ($request->attachments != null) 

当我发送 my_photo 时

            data.append('my_photo', 

只是将 my_photo 更改为附件解决了我的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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