React Native图像保存到php(laravel)服务器

时间:2019-11-04 06:40:18

标签: php laravel react-native

我正在尝试使用React Native将图像保存到php应用程序(由laravel 6.0制作)中。这是我的反应本机图像选择器

var ImagePicker = NativeModules.ImageCropPicker;

这是我的图像保存功能

addImages = async () => {
    const { image, images } = this.state
    const access_token = await AsyncStorage.getItem('access_token')

    try {

        let data = new FormData();

        images.map((image, i) => {
            data.append('id', id);
            data.append('uri', image.uri);
            data.append('type', image.mime);
            data.append('name', 'test.jpg');
        });

        fetch(apiConfig.apiUrl + '/api/save-image', {
            method: 'POST',
            headers: {        
                'Content-Type' : 'multipart/form-data',
                'Authorization': 'Bearer ' + access_token,
            },
            body:data
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {

                try {
                   console.log(data);                      

                } catch (error) {                     
                    console.log(error);
                }
            }.bind(this))
            .catch((error) => {
                console.log(error)
            });
    }catch (error) {
        console.log(error)
    }
}

这是我的php代码

public function saveImage(Request $request)
{
    header( "Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Origin: *");

    try {
        $file= array('file'=>$request->uri);
        Storage::disk('public')->put($request->imgName,File::get($file->file));

        return response()->json(['true'=>'Successfully Created'], 200);
    } catch (\Exception $e) {
        Log::info('vehicle image: ', [$e->getMessage()]);
        return response()->json(['error'=>$e], 200);
    }
}

当我尝试保存时,我得到SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

当我退回$request->uri时,我得到的是这样的file:///data/user/0/com.carup/cache/react-native-image-crop-picker/IMG_20191103_161929.jpg

我该如何解决?

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您需要将文件名指定为data.append的第三个参数:

data.append('file', image.uri, 'test.jpg');

答案 1 :(得分:0)

最后,我用Base64方法修复了它。这是我的代码。

使用base64选择图像

  pickMultipleBase64=()=> {
    ImagePicker.openPicker({
        multiple: true,
        width: 300,
        height: 300,
        includeBase64: true,
        includeExif: true,
    }).then(images => {
        this.setState({
            images: images.map(image => {
               return {uri: `data:${image.mime};base64,`+ image.data, width: image.width, height: image.height,type:image.mime}
            }),
        });

    }).catch(e => alert(e));
}

并上传了其他类似信息

addImages = async () => {
    const { image, images, stockNo } = this.state
    const access_token = await AsyncStorage.getItem('access_token')
    if(access_token == null) {
        return(
            this.gotoLogin()
        )
    }
    this.setState({
        isLoading:true,
        message:'',
        status:true
    })
    try {
        let data = new FormData();
        images.map((image, i) => {

            data.append('id', id);
            data.append('stock', stockNo);
            data.append('chassis', chassis_no);
            data.append('file'+i, this.state.images[i].uri);
            data.append('type'+i, this.state.images[i].type);

            imageCount++
        });

        data.append('imageCount', imageCount);

        // console.log(data);
        fetch(apiConfig.apiUrl + '/api/save-image', {
            method: 'POST',
            headers: {
               'Authorization': 'Bearer ' + access_token,
            },
            body:data
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                console.log(data);
                imageCount = 0
                try {
                    this.setState({
                        isLoading: false,
                        message:data.true ? data.true:data.error,
                        messageColor:data.true ? CarColors.success : CarColors.error,
                        btnStatus:true
                        // chassis:''
                    })

                    if(data.true){
                        this.setState({
                            image:null,
                            images: null,
                        })
                    }
                } catch (error) {
                    this.removeToken();
                    console.log('1 '+error);
                }
            }.bind(this))
            .catch((error) => {
                this.setState({
                    isLoading: false,
                    message:'error',
                    messageColor:CarColors.error,
                })
                console.log(error)
            });

    }catch (error) {
        console.log(error)
    }

我的php(laravel)代码是这样的。在这里,我在存储中创建了一个新文件夹(带有车辆ID),并将图像保存到单独的文件夹中。

public static function saveImage($request)
{
    $dir = "./storage/vehicle/" . $request->id;

    if (is_dir($dir) === false) {

        mkdir($dir);
    }
    DB::beginTransaction();
    try {

        for ($i = 0; $i < $request->imageCount; $i++) {

            $type = [];
            $file = 'file' . $i;
            $mime = 'type' . $i;
            $data = $request->$file;
            $type = explode('/', $request->$mime);
            $extension = $type[1];
            list($type, $data) = explode(';', $data);
            list(, $data) = explode(',', $data);
            $data = base64_decode($data);
            $Imgdata =Images::create([
                'vehicle_id' => $request->id,
                'img_name' => $i.'.'.$extension,
                'img_ext' => $extension,
                'img_order' => '0',
            ]);
            Storage::disk('vehicle')->put($request->id . '/' . $i . '.' . $extension, $data);
        }
        //Update Vehicle table ImageStatus

        $Vehicle = Vehicle::where('id',$request->id)->update([
            'img_status' => '1',
        ]);

        return response()->json(['true' => 'Successfully Uploaded'], 200);
    } catch (\Exception $e) {
        DB::rollback();
        Log::info('vehicle image name save issue: ', [$e->getMessage()]);
        return 'false';
    }
}

希望这将有助于其他人使用本机反应上传多张图片