上传文档时反应本机获取抛出错误

时间:2020-06-20 22:06:39

标签: android react-native

我正在尝试使用react native中的react-native-document-picker上传文件。上载时出现错误“可能未处理的承诺拒绝(id:0): TypeError:网络请求失败”。

当我尝试使用访存将数据发布到表中时,它工作正常。数据被发布,没有任何错误或警告。

完整代码

import React, { useState } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import { TextInput } from 'react-native-gesture-handler';

const FormScreen = () => {
let [singleFile, setSingleFile] = useState(null);
let [singleFile1, setSingleFile1] = useState(null);
let [singleFile2, setSingleFile2] = useState(null);

const [intialForm, setForm] = useState("");

let uploadImage = async () => {
//Check if any file is selected or not
if (singleFile != null) {
  console.log('Submitted');
  //If file selected then create FormData
  const fileToUpload = singleFile;
  let data = new FormData();
  data.append('name', 'Image Upload');
  data.append('type', 'image/jpeg');
  data.append('file_attachment', fileToUpload);
  //Please change file upload URL
  let res = await fetch(
    'https://acc.nwlz.com/inc/upload.php', //sample url
    {
      method: 'post',
      body: data,
      headers: {
        'Content-Type': 'multipart/form-data; ',
      },
    }
  );
  let responseJson = await res.json();
  if (responseJson.status == 1) {
    alert('Upload Successful');
  }
  } else {
  //if no file selected the show alert
  alert('Please Select File first');
  }
  };

  let selectFile = async () => {
  //Opening Document Picker to select one file
  try {
  const res = await DocumentPicker.pick({
    //Provide which type of file you want user to pick
    type: [DocumentPicker.types.allFiles],
    //There can me more options as well
    // DocumentPicker.types.allFiles
    // DocumentPicker.types.images
    // DocumentPicker.types.plainText
    // DocumentPicker.types.audio
    // DocumentPicker.types.pdf
  });
  //Printing the log realted to the file
  console.log('res : ' + JSON.stringify(res));
  //Setting the state to show single file attributes
  setSingleFile(res);
} catch (err) {
  setSingleFile(null);
  //Handling any exception (If any)
  if (DocumentPicker.isCancel(err)) {
    //If user canceled the document selection
    alert('Canceled from single doc picker');
  } else {
    //For Unknown Error
    alert('Unknown Error: ' + JSON.stringify(err));
    throw err;
  }
  }
  };


   return (
   <View style={styles.mainBody}>
  <View style={{ alignItems: 'center' }}>
    <Text style={{ fontSize: 30, textAlign: 'center' }}>
      Submit Forms
    </Text>
    <TextInput
          style={{backgroundColor:'#d2d2d2', marginBottom:10, width:300, 
   color:'#fff'}}
          
          placeholder="Enter Form Type Ex. 1.12"
          value = {intialForm}
          onChangeText = { (newtype) => setForm(newtype) }
          />
   
  </View>
  {/*Showing the data of selected Single file*/}
  {singleFile != null ? (
    <Text style={styles.textStyle}>
      File Name: {singleFile.name ? singleFile.name : ''}
      {'\n'}
      
    </Text>
  ) : null}
  {singleFile1 != null ? (
    <Text style={styles.textStyle}>
      File Name: {singleFile1.name ? singleFile1.name : ''}
      {'\n'}
      
    </Text>
  ) : null}
  {singleFile2 != null ? (
    <Text style={styles.textStyle}>
      File Name: {singleFile2.name ? singleFile2.name : ''}
      {'\n'}
      
    </Text>
  ) : null}
  <TouchableOpacity
    style={styles.buttonStyle}
    activeOpacity={0.5}
    onPress={selectFile}>
    <Text style={styles.buttonTextStyle}>Select File 1</Text>
  </TouchableOpacity>
 
  
  
  <TouchableOpacity
    style={styles.buttonStyle}
    activeOpacity={0.5}
    onPress={uploadImage}>
    <Text style={styles.buttonTextStyle}>Upload File</Text>
  </TouchableOpacity>
</View>
  );
  };

  const styles = StyleSheet.create({
  mainBody: {
  flex: 1,
  justifyContent: 'center',
  padding: 20,
  },
  buttonStyle: {
  backgroundColor: '#307ecc',
  borderWidth: 0,
  color: '#FFFFFF',
  borderColor: '#307ecc',
  height: 40,
  alignItems: 'center',
  borderRadius: 30,
  marginLeft: 35,
  marginRight: 35,
  marginTop: 15,
  },
  buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
textStyle: {
backgroundColor: '#fff',
fontSize: 15,
marginTop: 16,
marginLeft: 35,
marginRight: 35,
textAlign: 'center',
},
});

export default FormScreen;

我收到的错误消息是

Possible Unhandled Promise Rejection (id: 11):
TypeError: Network request failed
onerror@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28005:31
dispatchEvent@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:34133:31
setReadyState@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:33217:33
__didCompleteResponse@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:33044:29
emit@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3420:42
__callFunction@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2748:49
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2470:31
__guard@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2702:15
callFunctionReturnFlushedQueue@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2469:21
callFunctionReturnFlushedQueue@[native code]

我想将图像上传到我的服务器。

0 个答案:

没有答案