我如何使用react native expo image将图像上传到本地服务器PHP /数据库MySQL

乔维塔·苏坦托(Jovita Sutanto)

我正在使用expo客户端制作一个移动应用程序,以允许用户上传图像或从相机拍摄,然后将图像保存在PHP /数据库MySQL上的本地服务器上。如果我正在使用博览会,该怎么办?

例如react native中的代码(保存到PHP本地服务器但不保存数据库)

import React, { Component } from 'react';
import {
  ActivityIndicator,
  Button,
  Clipboard,
  Image,
  Share,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { Constants } from 'expo';
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';

export default class App extends Component {
  state = {
    image: null,
    uploading: false,
  };

  render() {
    let {
      image
    } = this.state;

    return (
      <View style={styles.container}>
        <StatusBar barStyle="default" />

        <Text
          style={styles.exampleText}>
          Example: Upload ImagePicker result
        </Text>

        <Button
          onPress={this._pickImage}
          title="Pick an image from gallery"
        />

        <Button onPress={this._takePhoto} title="Take a photo" />

        {this._maybeRenderImage()}
        {this._maybeRenderUploadingOverlay()}
      </View>
    );
  }

  _maybeRenderUploadingOverlay = () => {
    if (this.state.uploading) {
      return (
        <View
          style={[StyleSheet.absoluteFill, styles.maybeRenderUploading]}>
          <ActivityIndicator color="#fff" size="large" />
        </View>
      );
    }
  };

  _maybeRenderImage = () => {
    let {
      image
    } = this.state;

    if (!image) {
      return;
    }

    return (
      <View
        style={styles.maybeRenderContainer}>
        <View
          style={styles.maybeRenderImageContainer}>
          <Image source={{ uri: image }} style={styles.maybeRenderImage} />
        </View>

        <Text
          onPress={this._copyToClipboard}
          onLongPress={this._share}
          style={styles.maybeRenderImageText}>
          {image}
        </Text>
      </View>
    );
  };

  _share = () => {
    Share.share({
      message: this.state.image,
      title: 'Check out this photo',
      url: this.state.image,
    });
  };

  _copyToClipboard = () => {
    Clipboard.setString(this.state.image);
    alert('Copied image URL to clipboard');
  };

  _takePhoto = async () => {
    const {
      status: cameraPerm
    } = await Permissions.askAsync(Permissions.CAMERA);

    const {
      status: cameraRollPerm
    } = await Permissions.askAsync(Permissions.CAMERA_ROLL);

    // only if user allows permission to camera AND camera roll
    if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
      let pickerResult = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        aspect: [4, 3],
      });

      this._handleImagePicked(pickerResult);
    }
  };

  _pickImage = async () => {
    const {
      status: cameraRollPerm
    } = await Permissions.askAsync(Permissions.CAMERA_ROLL);

    // only if user allows permission to camera roll
    if (cameraRollPerm === 'granted') {
      let pickerResult = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [4, 3],
      });

      this._handleImagePicked(pickerResult);
    }
  };

  _handleImagePicked = async pickerResult => {
    let uploadResponse, uploadResult;

    try {
      this.setState({
        uploading: true
      });

      if (!pickerResult.cancelled) {
        uploadResponse = await uploadImageAsync(pickerResult.uri);
        uploadResult = await uploadResponse.json();

        this.setState({
          image: uploadResult.location
        });
      }
    } catch (e) {
      console.log({ uploadResponse });
      console.log({ uploadResult });
      console.log({ e });
      alert('Upload failed, sorry :(');
    } finally {
      this.setState({
        uploading: false
      });
    }
  };
}

async function uploadImageAsync(uri) {
  let apiUrl = 'http://192.168.0.18/upload-api/uploading.php';
  let uriParts = uri.split('.');
  let fileType = uriParts[uriParts.length - 1];

  let formData = new FormData();
  formData.append('fileToUpload', {
    uri,
    name: `fileToUpload.${fileType}`,
    type: `image/${fileType}`,
  });

  let options = {
    method: 'POST',
    body: formData,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
  };

  return fetch(apiUrl, options);
}

这是我的PHP

  <?php
   $target_dir = 'uploads/';
   $target_file = $target_dir . basename($_FILES['fileToUpload']['name']);

   $status = array();

   if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
   $status['status']=1;
   $status['description']='upload success';
  } else {
   $status['status']=0;
   $status['description']='upload failed';
  }
   echo json_encode($status);

  ?> 

有什么解决办法吗?谢谢

努鲁丁·拉哈尼(Nooruddin Lakhani)

您可以使用Fetch Api上传图片

var photo = {
  uri: selectImg.localUri,
  type: 'image/jpeg',
  name: 'photo.jpg',
};

var form = new FormData();
form.append("ProfilePicture", photo);

fetch(
  Constants.API_USER + 'me/profilePicture',
  {
    body: form,
    method: "PUT",
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + user.token
    }
  }
).then((response) => response.json())
.catch((error) => {
  alert("ERROR " + error)
})
.then((responseData) => {
  alert("Succes "+ responseData)
}).done();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将 react-native 图像从 expo-image-picker 上传到使用 multer 的 Express.js 后端

如何使用Expo在React Native中从DocumentPicker打开SQLite数据库

如何在React Native中使用上传图像将数据获取到PHP服务器

如何在React Native中使用axios将图像上传到服务器?

本地数据库+服务器数据库-React Native

使用放大存储将图像错误上传到s3(React Native-Expo-Amplify)

我应该使用Expo作为Expo音频库还是React-native-track-player?

如何在React native中加密数据(使用Expo)

React-native通过Expo ImagePicker将图像上传到AWS S3

如何将文件上传到数据库,而不仅仅是使用php的服务器

我如何将Expo组件整合到非expo React Native应用中?

将文件从react-native(expo)项目上载到php服务器(laravel)

如何使用React Native和Expo显示图像?

如何使用PHP代码将图像上传到MySQL数据库

如何在React Native中使用expo-image-picker上传图像

本地git存储库以及如何将HTML和PHP代码上传到Web服务器

react native expo 从对象读取数据

React Native EXPO Apple上传失败

如何从Android程序将SQLite数据库文件上传到FTP服务器

如何将sqlite3数据库上传到Web服务器?

从React Native和Expo调用本地域

在 React Native (Expo) 中显示 blob 图像

图像未显示 React Native Expo

如何使用Android Volley库将位图图像上传到服务器?

React Native中的Expo-Image-Picker

将图像上传到服务器并将图像路径存储在mysql数据库中

如何将React Native Expo App上传到Windows 10上的App Store?

使用 React Native Expo 将 mp3 上传到 Firebase 存储

如何在React Native上访问本地数据库?