React Native 使用提取尝试图像上载时出现formData问题

46qrfjad  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(120)

我正在尝试从React Native上传一个图像到服务器。我使用了一个“picker”(react-native-document-picker)来选择图像,该部分似乎可以正常工作。下面是我使用的代码:

import React, { Component } from "react";
import { Button, Dimensions, Image, Platform, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

import DocumentPicker from 'react-native-document-picker';

const SERVER_URL = 'http://localhost:3000';

export default class Images extends Component {
constructor(props) {
  super(props);

  this.state = {
    photo: null,
  };
}

   ChoosePhoto = async () => {

    try {

    const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.images], });

    this.setState({ photo: res });  //Set the state to the selected file attributes

    } catch (err) {
    this.setState({ photo: null });
  
      if (DocumentPicker.isCancel(err)) {
        alert('Canceled');  //user canceled the document selection
      } else {
        alert('Selection Error: ' + JSON.stringify(err));  //Unknown Error
      }  //Handling any exception (if any)

    }  //try routine

  };

  UploadPhoto = async () => {

   if (this.state.photo != null) {

   //if file selected then create FormData

   const fileToUpload = this.state.photo.uri;

   const data = new FormData();
   data.append('name', 'Image Upload');
   data.append('type', this.state.photo.type);
   data.append('file_attachment', fileToUpload);

   console.log("data.name is: " + data.name);  //"undefined"
   console.log("data.type is: " + data.type);  //"undefined"
   console.log("data.file_attachment is: " + data.file_attachment);  //"undefined"
   console.log("fileToUpload is: " + fileToUpload);  //correct

     //****UPLOAD TO SERVER

     fetch(`${SERVER_URL}/api/upload`, {
       method: 'POST',
       body: data,
       headers: { 'Content-Type': 'multipart/form-data' }
     })
     .then((response) => response.json())
     .then((response) => {
      console.log('Upload success: ', response);
      alert('Upload success!');
      this.setState({ photo: null });
     })
     .catch((error) => {
      this.setState({ photo: null });
      this.setState({ notify: "Pending Upload..." });
      console.log('Upload error: ', error);
      alert('Upload failed!');
     });

     //****

   } else {
   alert('Please Select File to Upload...');
   }  //'this.state.photo' is NOT NULL...OR NOT...

  };

...

}  //class 'Images' Component

从我的评论中可以看出,FormData定义之后的'console.log'语句和'.append'语句都是“未定义的”(在'UploadPhoto'函数中)...甚至连设置为简单字符串('Image Upload')的'name'也没有定义。因此,很明显整个FormData命令完全不起作用。
我花了几天时间试图弄清楚这一点...很难相信在2023年这样的事情会如此错综复杂。我以前从网络应用程序上传图像几乎没有困难,但这是我第一次尝试使用“FormData”并尝试从React Native上传文件。
任何建议都将受到极大的赞赏。我先谢谢你。

vu8f3i0k

vu8f3i0k1#

要访问FormData中的值,请使用get

const data = new FormData();
data.append('name', 'Image Upload');
console.log("data.name is: " + data.get("name"));

上载文件的步骤

const body = new FormData()
body.append('file', {uri: 'path/to/content', type: 'type', name: 'name'})
const response = await fetch('url', {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body: body
})

相关问题