【问题标题】:how can i upload image using react native expo image to my local server PHP / Database MySQL我如何使用 react native expo image 将图像上传到我的本地服务器 PHP / Database MySQL
【发布时间】:2021-01-28 15:10:06
【问题描述】:

我正在使用 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);

  ?> 

有什么解决办法吗?谢谢

【问题讨论】:

  • 您可以使用busboy 将图像上传到您的数据库。
  • 好的。如果我使用纱线?它仍然可以上传到我的服务器吗?
  • yarn 只是一个包管理器。您必须设置后端才能将其上传到您的数据库。

标签: php reactjs database react-native expo


【解决方案1】:

您可以使用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();

【讨论】:

  • 感谢您的回答。它在方法帖子上工作吗?
猜你喜欢
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 2021-12-31
  • 2021-06-07
  • 2021-05-29
  • 2020-09-07
  • 2020-09-16
  • 2020-04-09
相关资源
最近更新 更多