【问题标题】:How to upload file in React native with imagepack如何使用 imagepack 在 React Native 中上传文件
【发布时间】:2020-07-31 22:16:54
【问题描述】:

我想在服务器上上传一张图片,它出现在预览中,但它是在 request.body 中发送的,但我希望它是在 request.file 中发送的。我究竟做错了什么?我在反应中将它发送到网络,我没有问题,只有在本机反应中。当我发送 request.body 时,文件作为 [Object] [Object],但我想从通过手机发送的文件中提取路径和图像。

index.js

import React, { useState, useEffect } from "react";
import { useNavigation } from "@react-navigation/native";
import * as ImagePicker from "expo-image-picker";
import Constants from "expo-constants";

import {
  View,
  Image,
  TextInput,
  Text,
  TouchableOpacity,
  Picker,
  ScrollView,
  Alert,
} from "react-native";
import api from "../../services/api";
import logoImg from "../../assets/icon.png";
import styles from "./styles";

export default function NewProvider() {
  const [name, setName] = useState("");
  const [avatar, setAvatar] = useState(null);
  const [pickerVisible, setPickerVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  async function handleSubmit() {
    try {
      setLoading(true);
      let localUri = avatar.uri;
      let filename = localUri.split("/").pop();
      let match = /\.(\w+)$/.exec(filename);
      let typeImg = match ? `image/${match[1]}` : `image`;
      let formdata = new FormData();
      formdata.append("avatar", {
        type: typeImg,
        uri: localUri,
        name: filename,
      });
      formdata.append("name", name);
      await api.post("/providers", formdata, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      
    } catch (err) {
      console.log(err)
    }
    setLoading(false);
  }
  async function getPermissionAsync() {
    if (Constants.platform.ios) {
      const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (status !== "granted") {
        alert("Sorry, we need camera roll permissions to make this work!");
      }
    }
  }
  async function pickImage(e) {
    try {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
        base64: true,
      });
      if (!result.cancelled) {
        setAvatar(result);
      }
    } catch (err) {
      console.log("erro", err);
    }
  }
 
  useEffect(() => {
    getPermissionAsync();
  }, []);
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Image style={styles.logoImage} source={logoImg} />
      </View>
      <Text style={styles.loginTitle}>Cadastrar prestador de serviço</Text>
      <View style={styles.login}>
        <ScrollView
          vertical
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={{ paddingHorizontal: 20 }}
        >
          <TextInput
            placeholder="* Nome do(a) prestador(a)/empresa"
            onChange={(e) => setName(e.target.value)}
            style={styles.inputForm}
            value={name}
           
          />
          <View
            style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
          >
            <TouchableOpacity style={styles.getImage} onPress={pickImage}>
              <Text style={styles.imageText}>Selecione uma imagem</Text>
            </TouchableOpacity>
            {avatar && (
              <Image
                source={{ uri: avatar.uri }}
                style={{ width: 200, height: 200, marginTop: 20 }}
              />
            )}
          </View>
          <TouchableOpacity style={styles.action} onPress={handleSubmit}>
            <Text style={styles.actionText}>
              {loading ? "Enviando..." : "Cadastrar"}
            </Text>
          </TouchableOpacity>
        </ScrollView>
      </View>
    </View>
  );
}

【问题讨论】:

    标签: javascript node.js react-native express expo


    【解决方案1】:

    通过查看您的代码,我认为有更好的方法。

    首先我建议创建一个函数来处理ImageUpload 如下图

    handleUploadPhoto = () => {
      fetch("http://localhost:3000/api/upload", {
        method: "POST",
        body: createFormData(this.state.photo, { userId: "123" })
      })
        .then(response => response.json())
        .then(response => {
          console.log("upload succes", response);
          alert("Upload success!");
          this.setState({ photo: null });
        })
        .catch(error => {
          console.log("upload error", error);
          alert("Upload failed!");
        });
    };
    

    这将强制 react native 将图像作为 request.file 而不是 request.file 发送,如果一切顺利,它会检查你的控制台,看看它是否显示成功!

    要调用它,你可以使用类似这样的东西

    <Button title="Upload" onPress={this.handleUpload} />
    

    现在请记住,这是一个示例,请根据您的需要进行更改。

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多