将本机图像上传反应为表单数据

2024-05-27

Postman formdata 工作正常,但是返回 http 500 错误。这个块出了什么问题。

响应 {type: "default", status: 500, ok: false, statusText: 未定义,标头:标头,...}标头:标头{map:{...}}确定: falsestatus:500statusText:未定义类型:“默认”url: ”http://cupdes.com/api/v1/create-user http://cupdes.com/api/v1/create-user“_bodyInit:””_bodyText: ””proto:对象“rtghj”

import React, {Component} from 'react';
import {Platform, StyleSheet,View,Image,ScrollView,TextInput,KeyboardAvoidingView,TouchableOpacity,TouchableHighlight,AsyncStorage,} from 'react-native';
import { Container, Header, Content, Button, Text,Input, Label,Item,Form, } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-picker';

export default class SignUp extends Component {
  constructor(){
    super();
    this.state = {
      email: "",
      name: "",
      password: "",
      photo: null ,

      errors: [],
      showProgress: false,
    }
}
handleChoosePhoto = () => {
  const options = {
    noData: true,
  };
  ImagePicker.launchImageLibrary(options, response => {
    if (response.uri) {
      this.setState({ photo: response });
    }
  });
};

onPressSubmitButton() {
  console.log("Image ",this.state.photo,this.state.email,this.state.password,this.state.name)
  this.onFetchLoginRecords();
} 

async onFetchLoginRecords() {



const createFormData = () => {
  var data = new FormData();

  data.append("image", {
    name: this.state.photo.fileName,
    type: this.state.photo.type,
    uri:
      Platform.OS === "android" ? this.state.photo.uri : this.state.photo.uri.replace("file://", "")
  });
  data.append('name', this.state.name);
  data.append('password',this.state.password);
  data.append('email', this.state.email);
  console.log("aaaa",data);
  return data;
};


try {
  let response = await fetch(

   'http://cupdes.com/api/v1/create-user',
   {
     method: 'POST',
     headers: {
      'X-AUTH-TOKEN': 'Px7zgU79PYR9ULEIrEetsb',
      'Content-Type': 'multipart/form-data'

     },
    body:createFormData() 

  }
 )
 .then((response) => {
 console.log(response,"rtghj") 
 this.setState({ photo: null });
 if (JSON.parse(response._bodyText) === null) {
  alert("Internal server error!!!");
 }else{
  if (JSON.parse(response._bodyText).success === "true") {
    this.props.navigation.navigate('loading');
   }else{

    alert("Data missing!!!");
 }
}

 })

     } catch (errors) {
    alert(errors);
} 
}    SignupHandler=()=>{
        this.props.navigation.navigate('DrewerNav')
    }
    SignuptologinHandler=()=>{
        this.props.navigation.navigate('SigntoLogin')
    }
  render() {
    const { photo } = this.state;
    return (

      <KeyboardAvoidingView
      style={styles.wrapper}
      >

        <View style={styles.scrollWrapper}>
 <ScrollView style={styles.scrollView}>
 <View style={styles.LogoContainer}>
 <Image source={require('../Images/avatar1.png')} style={styles.Logo}  onPress={this.handleChoosePhoto} />

 <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>

        {photo && (
          <Image
            source={{ uri: photo.uri,
              type: "image/jpeg",
              name: photo.filename  }}
            style={{ width: 125, height: 125,borderRadius:80}}

          />

        )
        }
      <TouchableOpacity >
        <Icon  name="image" size={30} color="#222" marginTop='30' position='absolute' onPress={this.handleChoosePhoto}position='relative'/>
          </TouchableOpacity>
      </View> 
        <Text style={styles.createNew1}>  CREATE ACCOUNT</Text>  
        </View>
        <View>

        <Form style={styles.inputwrapper} >

            <Item  >
            <Icon  name="user" size={25} color="white"/>
              <Input     style={styles.input}
                          placeholder='Your name'
                          placeholderTextColor={'white'}
                         name="name"
                         onChangeText={text => this.setState({ name: text })}
              />
            </Item>
            <Item >
            <Icon  name="mail-bulk" size={25} color="white"/>
              <Input style={styles.input}
                      placeholder='Your e-mail'
                      placeholderTextColor={'white'}
                    name="email"
                    onChangeText={text => this.setState({ email: text })}
               />
            </Item>
            <Item   >
            <Icon  name="lock" size={25} color="white"/>
              <Input  style={styles.input}
                      secureTextEntry 
                      placeholder='Your password'
                      placeholderTextColor={'white'}
                      name="password"
                      onChangeText={text => this.setState({ password: text })}
              />
            </Item >
            <Item  >
            <Icon  name="unlock" size={25} color="white"/>
              <Input  style={styles.input}
                      secureTextEntry 
                      placeholder='Confirm password'
                      placeholderTextColor={'white'}
                      name="password"
              />
            </Item>
          </Form>
        </View>
        <View>
          <TouchableOpacity >
          <Button style={styles.btnLogin} onPress={this.onPressSubmitButton.bind(this)}

    >
            <Text style={styles.text} >Sign Up </Text>
            </Button>
          </TouchableOpacity>
          <TouchableOpacity onPress={this.SignuptologinHandler}  >
          <Text style={styles.createNew}>  Have an account ?LOG IN</Text>  
          </TouchableOpacity>
      </View>
      </ScrollView>
 </View>
      </KeyboardAvoidingView>
    );
  }
}

我可能很晚才发布答案,但这可能对遇到相同错误的其他人有帮助。以下工作流程对我有用。我使用 Node.js 作为后端。


const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true,
        path: 'images',
        cameraRoll: true,
        waitUntilSaved: true,
      },
    };


ImagePicker.showImagePicker(options, response => {
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {

        let source = response;
        this.setState({profileImage: source});
      }
    });
  }

saveToServer(){
let {profileImage} = this.state;
// initilizing form data

let formData = new FormData();

formData.append('file', {
        uri: profileImage.uri,
        type: 'image/jpeg/jpg',
        name: profileImage.fileName,
        data: profileImage.data,
      });

    axios.post('http://192.156.0.22:3000/api/updateProfile', userDetail, {
      headers: {'Content-Type': 'multipart/form-data'},
    }).then(res => //)
      .catch(err => //);
}

在节点服务器中,我正在做类似的事情。

//index.js
//..
const formData = require('express-form-data');
//..
//
app.use(formData.parse());
// profile.js
profile.post('/updateProfile', async (req, res) => {
let imageCloud = await cloudinary.v2.uploader.upload(req.files.file.path, {
        use_filename: true
      });
}

注意:我使用 cloudinary 来存储我的图像。 上面的代码适用于 Android 和 iOS。

我希望这能在一定程度上帮助你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将本机图像上传反应为表单数据 的相关文章

随机推荐

  • 如何使用 PyGithub 创建新存储库

    如何使用 PyGithub 在 Github 上创建新的存储库 我特别想知道如何使用create repo http jacquev6 net PyGithub v1 github objects AuthenticatedUser htm
  • Spring Security:推迟使用 HTTP 基本身份验证之前的 IP 地址白名单

    我有一个可通过 servlet 访问的 URL 我已使用 Spring Security 的 DaoAuthenticationProvider 锁定该 URL 我现在要求某些传入 IP 地址必须列入白名单 因此不需要进行身份验证 如果 I
  • 运行 Sqoop 导入和导出时如何找到最佳映射器数量?

    我正在使用 Sqoop 版本 1 4 2 和 Oracle 数据库 运行 Sqoop 命令时 例如这样 sqoop import fs
  • 检查 listbox1 中是否已存在某个项目

    在 form1 中 我有两个列表框 listbox1 listbox2 加载按钮和保存按钮 此代码会将 listbox1 selecteditem 写入 txt 文件 然后 loadbutton 将加载信息 但在 listbox2 中我希望
  • 当值设置为该值时,如何在 Code Mirror 中格式化 HTML 代码?

    我正在使用 Code Mirror 插件来编辑页面的 HTML 源代码 HTML 代码从数据库中获取并设置为 Code Mirror 中的值 但是 设置值后 它会以与保存在数据库中相同的格式显示 如何以正确的格式显示它 提前致谢 有一个函数
  • C++,最佳实践,int 还是 size_t? [复制]

    这个问题在这里已经有答案了 可能的重复 何时使用 std size t https stackoverflow com questions 1951519 when to use stdsize t hello 假设使用模式相同 即没有负数
  • 如何在 Durandal 中为我的 shell 视图模型使用类?

    我正在查看 Hot Towel 模板 并试图让它在 TypeScript 中工作 但我在转换 shell 视图模型时遇到了问题 我正在尝试将其转换为 TS 对我来说更有意义的是它应该是一个类 而不是简单地导出如图所示的函数here http
  • 拖动 Window 时无法可靠地调用 LocationChanged

    为了实现对接 我依靠监听 Window LocationChanged 事件来检测在屏幕上拖动的窗口的位置变化 但一位用户报告说 对接在他们的机器上无法工作 事实证明 他们在 Windows 性能选项中禁用了 拖动时显示窗口内容 因此只有在
  • EF 迁移迁移到 0 调用初始创建关闭

    我正在尝试找出将迁移降低到空数据库的语法 就像在初始创建迁移中调用 down 方法一样 有谁知道在迁移中调用 Down 方法的正确语法与此类似 Update Database StartupProjectName Infrastructur
  • 如何更改 WordPress 的 TinyMCE 默认字体

    我在 SO 上看到这个问题 但所有答案都未能具体说明如何改变这一点 我的意思是这样的 答案说 添加这个 但他们无法告诉我在哪里 我的意思是 哪个文件 并且必须是一名火箭科学家才能弄清楚 有人可以解释一下吗就像我五岁一样 好吧 设为 3 我必
  • 根据三列中的值组织行

    导入并获取数据集import numpy as np import matplotlib pyplot as plt import pandas as pd df pd DataFrame DaysExperienceTask 7 8 2
  • WinRT 中的当前文化是错误的

    我正在尝试使用 WinRT 中的当前文化来格式化日期时间值 但CurrentCulture属性似乎并不尊重系统文化 我尝试了以下两个属性 System Globalization CultureInfo CurrentCulture Dis
  • Ruby 中 SecureRandom.urlsafe_base64(8) 的碰撞概率?

    我在用SecureRandom urlsafe base64 8 为了在我的系统中创建 URL 安全的唯一 ID 我想知道如何计算碰撞概率 我将大约 10 000 个这些 id 插入到一个数组中 我想避免检查其中一个键是否已经在数组中 但我
  • JavaScript 的 eval() 什么时候不是邪恶的?

    我正在编写一些 JavaScript 代码来解析用户输入的函数 用于类似电子表格的功能 解析了公式我could将其转换为 JavaScript 并运行eval 就可以得到结果了 然而 我一直回避使用eval 如果我可以避免它 因为它是邪恶的
  • 导航栏是垂直的而不是水平的

    div div
  • 在 Objective C 中使用 NSMutableArray 对象的指针

    当在 cocoa touch 中从 NSMutableArray 检索对象时 下面的代码可以吗 我应该每次分配 alloc 新的 Page 对象还是只是指向它 我是否需要对 Page pageObj 之后执行任何操作 例如将其设置为 nil
  • 使用 .NET WebClient 模拟 XmlHttpRequest

    据我所知XmlHttpRequest我只需使用以下命令即可下载和上传数据send方法 但WebClient有很多方法 我不想要一个的所有功能WebClient 我只想创建一个模拟的对象XmlHttpRequest 但它没有 XSS 限制 我
  • asp.net 检查 imageURL 是否存在

    我正在尝试从另一个 Intranet 站点获取用户的缩略图 但其中一些不遵循预定义的格式 这意味着我想加载默认的缩略图 检查图像 URL 是否有效的最佳方法是什么 根据您获取图像的方式 此方法的变体可能会起作用 img src alt My
  • RestKit:BOOL 值

    我有一个NS ENUM保存清单的状态 这两个属性是Pending and Completed typedef NS ENUM NSUInteger ChecklistStatus Pending Completed 我正在尝试获取状态并将其
  • 将本机图像上传反应为表单数据

    Postman formdata 工作正常 但是返回 http 500 错误 这个块出了什么问题 响应 type default status 500 ok false statusText 未定义 标头 标头 标头 标头 map 确定 f