React Native Expo项目上传文件

这篇具有很好参考价值的文章主要介绍了React Native Expo项目上传文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

React Native Expo项目上传文件,web前端,react native,react.js,javascript

React Native Expo项目上传文件,web前端,react native,react.js,javascript 

 React Native Expo项目上传文件,web前端,react native,react.js,javascript

 

Index.js:

import React from 'react'
import {
  ScrollView,
  View,
  TouchableWithoutFeedback,
  Text,
  Image,
} from 'react-native'
import { WebView } from 'react-native-webview'
import style from './style.js'
import { Icon } from '../../../component/light'
import { Divider, LinearProgress, Button, Input, Dialog } from '@rneui/themed'
import useList from './useList.js'

export default function Index(props) {
  const {
    username,
    emailCode,
    isSendEmail,
    count,
    avatar,
    nickname,
    password,
    code,
    visible,
    isLoading,
    captcha,
    visible1,
    usernameEl,
    setEmailCode,
    handleSendEmail,
    setNickname,
    setPassword,
    setCode,
    toggleDialog1,
    handleInput,
    handleLogin,
    handleNav,
    handleVisilbe,
    handleUploadAvatar,
    getCaptcha,
    pickFile,
  } = useList(props)

  return (
    <ScrollView style={style.mRegisterWrap}>
      <LinearProgress
        style={[style.mLoading, isLoading ? style.mLoadingActive : {}]}
        color="primary"
      />
      <View style={style.mRegisterInner}>
        <View style={style.mRegisterRow}>
          <Input
            label="邮箱"
            style={style.mRegisterInput}
            labelStyle={style.mRegisterLabelStyle}
            value={username}
            onChangeText={handleInput}
            placeholder="邮箱"
            // autoFocus
            ref={usernameEl}
            rightIcon={
              <Icon
                name={'help'}
                onPress={toggleDialog1}
                style={style.mInpntRightIcon}
              ></Icon>
            }
          ></Input>
        </View>
        <View style={style.mRegisterRow}>
          <Input
            label="邮箱验证码"
            style={style.mRegisterInput}
            labelStyle={style.mRegisterLabelStyle}
            value={emailCode}
            onChangeText={setEmailCode}
            placeholder="邮箱验证码"
            rightIcon={
              isSendEmail ? (
                <Button
                  title={`${count}秒后重新发送`}
                  disabled
                  containerStyle={style.mSendEmailBtn}
                />
              ) : (
                <Button
                  title="发送"
                  containerStyle={style.mSendEmailBtn}
                  onPress={handleSendEmail}
                />
              )
            }
          ></Input>
        </View>
        <View style={style.mRegisterRow}>
          <View style={style.mRegisterAvavtarTextWrap}>
            <Text style={style.mRegisterAvavtarText}>头像</Text>
          </View>
          {avatar ? (
            <TouchableWithoutFeedback onPress={handleUploadAvatar}>
              <Image
                source={{ uri: avatar }}
                style={style.mRegisterAvatar}
              ></Image>
            </TouchableWithoutFeedback>
          ) : (
            <View style={style.mRegisterUploadIcoWrap}>
              <Icon
                name={'add'}
                onPress={handleUploadAvatar}
                style={style.mRegisterUploadIcon}
              ></Icon>
            </View>
          )}
        </View>
        <View style={style.mRegisterRow}>
          <Input
            label="昵称"
            style={style.mRegisterInput}
            labelStyle={style.mRegisterLabelStyle}
            value={nickname}
            onChangeText={setNickname}
            placeholder="昵称"
          ></Input>
        </View>
        <View style={style.mRegisterRow}>
          <Input
            label="密码"
            style={style.mRegisterInput}
            labelStyle={style.mRegisterLabelStyle}
            value={password}
            onChangeText={setPassword}
            placeholder="密码"
            secureTextEntry={!visible}
          ></Input>
          <Icon
            name={visible ? 'show' : 'close'}
            onPress={handleVisilbe}
            style={style.mRegisterPasswordIcon}
          ></Icon>
        </View>
        <View style={style.mRegisterRow}>
          <Input
            label="验证码"
            style={style.mRegisterInput}
            labelStyle={style.mRegisterLabelStyle}
            value={code}
            onChangeText={setCode}
            placeholder="验证码"
          ></Input>
        </View>
        <View style={style.mRegisterCodeWrap}>
          <TouchableWithoutFeedback onPress={getCaptcha}>
            <WebView
              originWhitelist={['*']}
              source={{ html: captcha }}
            ></WebView>
          </TouchableWithoutFeedback>
        </View>

        <View style={[style.mRegisterBtnWrap]}>
          <Button onPress={handleLogin} type="solid" title="注册"></Button>
        </View>
        <View style={style.mRegisterMoreBtnWrap}>
          <Button
            containerStyle={style.mRegisterMoreBtn}
            onPress={() => handleNav('Login')}
            title="登录"
            type="clear"
          ></Button>
          <Button
            containerStyle={style.mRegisterMoreBtn}
            onPress={() => handleNav('IndexForTab')}
            title="游客"
            type="clear"
          ></Button>
        </View>
        <Divider width={1}></Divider>
        <Button title="上传文件" onPress={pickFile} />

        <Text style={style.mRegisterText}>注册</Text>

      </View>
      <Dialog isVisible={visible1} onBackdropPress={toggleDialog1}>
        <Dialog.Title title="提示" />
        <Text>某些用户的邮件会发送到垃圾箱</Text>
      </Dialog>
    </ScrollView>
  )
}

useList.js:

import { useState, useRef, useEffect } from 'react'
import Api from '../../../api'
import Constants from 'expo-constants'
import Toast from 'react-native-root-toast'
import { checkEmail } from '../../../utils/tools'
import AsyncStorage from '@react-native-async-storage/async-storage'
import * as ImagePicker from 'expo-image-picker'
import * as DocumentPicker from 'expo-document-picker'

let timer
export default function useList(props) {
  const [username, setUsername] = useState('')
  const [emailCode, setEmailCode] = useState('')
  const [isSendEmail, setIsSendEmail] = useState(false)
  const [count, setCount] = useState(0)
  const [emailId, setEmailId] = useState('')
  const [avatar, setAvatar] = useState(null)
  const [nickname, setNickname] = useState('')

  const [password, setPassword] = useState('')
  const [code, setCode] = useState('')
  const [visible, setVisible] = useState(false)
  // eslint-disable-next-line
  const [isLoading, setIsLoading] = useState(false)
  const [captchaId, setCaptchaId] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [visible1, setVisible1] = useState(false)
  const usernameEl = useRef(null)

  const { navigation } = props

  const toggleDialog1 = () => {
    setVisible1(!visible1)
  }
  const handleInput = (e) => {
    setUsername(e)
  }

  const handleSendEmail = () => {
    const { isEmail, message } = checkEmail(username)
    if (username.trim() === '') {
      Toast.show('邮箱不能为空', {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    } else if (isEmail === false) {
      Toast.show(message, {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    }

    Api.h5.userSendEmailCode({ username }).then((res) => {
      if (res.code === 200) {
        setEmailId(res.data.emailId)
        Toast.show(res.message, {
          duration: 3000,
          position: Toast.positions.CENTER,
        })
        setCount(Constants.manifest.extra.REACT_APP_MODE === 'dev' ? 6 : 180)
        setIsSendEmail(true)
        console.log('send11', res.data.emailId)
      }
    })
  }

  const handleLogin = () => {
    const { isEmail, message } = checkEmail(username)

    if (username.trim() === '') {
      Toast.show('用户名不能为空', {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    } else if (isEmail === false) {
      Toast.show(message, {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    } else if (password.trim() === '') {
      Toast.show('密码不能为空', {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    } else if (code.trim() === '') {
      Toast.show('验证码不能为空', {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    } else if (!emailId) {
      Toast.show('请获取邮箱验证码', {
        duration: 3000,
        position: Toast.positions.CENTER,
      })
      return
    }

    Api.h5
      .userAiAdd({
        username,
        emailCode,
        emailId,
        nickname,
        password,
        code,
        captchaId,
      })
      .then((res) => {
        if (res.code === 200) {
          navigation.navigate('Login')
        }
      })
  }

  const handleNav = (path) => {
    navigation.navigate(path)
  }

  const handleVisilbe = () => {
    setVisible(!visible)
  }

  const handleUploadAvatar = async () => {
    try {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        base64: true,
        //allowsEditing: true,
        //aspect: [4, 3],
        //quality: 1,
      })
      if (!result.canceled) {
        const formData = new FormData()
        let uri = result.assets[0].uri
        let uriArr = uri.split('/')
        let name = uriArr[uriArr.length - 1]
        console.log(uri)
        setAvatar(uri)
        formData.append('file', {
          uri,
          name,
          //type: result.assets[0].type,
          type: 'image/jpeg',
        })
        Api.h5
          .uploadFile(formData)
          .then((res) => {
            console.log(res)
            if (res.code === 200) {
              console.log('成功')
              Toast.show('上传成功', {
                duration: 3000,
                position: Toast.positions.CENTER,
              })
            }
          })
          .catch((err) => {
            Toast.show('上传失败', {
              duration: 3000,
              position: Toast.positions.CENTER,
            })
          })
      } else {
        console.log('取消文件选择')
      }
    } catch (error) {
      console.log('选择文件时出错', error)
    }
  }

  const getCaptcha = () => {
    console.log('captcha')
    Api.h5.userCaptcha({}).then((res) => {
      if (res.code === 200) {
        const { captchaId, captcha } = res.data
        let svg = captcha
        let height = svg.indexOf('height')
        let width = svg.indexOf('width')
        let step1 = svg.slice(0, height + 8)
        let step2 = svg.slice(height + 8 + 2)
        svg = `${step1}150${step2}`
        let step3 = svg.slice(0, width + 5)
        let step4 = svg.slice(width + 8 + 3)
        svg = `${step3}450${step4}`
        let html = `<div style="text-align:center;width:100%;overflow:hidden;">${svg}</div>`
        setCaptcha(html)
        setCaptchaId(captchaId)
      }
    })
  }

  const pickFile = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync()

      if (result.type === 'success') {
        // 执行文件上传的逻辑
        console.log(result.uri) // 上传文件的URI
        console.log(result.name) // 上传文件的名称
        console.log(result.size) // 上传文件的大小
        console.log(result.mimeType) // 上传文件的类型

        const formData = new FormData()
        let uri = result.uri
        let uriArr = uri.split('/')
        let name = uriArr[uriArr.length - 1]

        formData.append('file', {
          uri: result.uri,
          name: result.name,
          type: result.mimeType,
        })
        Api.h5
          .uploadFile(formData)
          .then((res) => {
            console.log(res)
            if (res.code === 200) {
              console.log('成功')
              Toast.show('上传成功', {
                duration: 3000,
                position: Toast.positions.CENTER,
              })
            }
          })
          .catch((err) => {
            Toast.show('上传失败', {
              duration: 3000,
              position: Toast.positions.CENTER,
            })
          })
      } else {
        console.log('取消文件选择')
      }
    } catch (error) {
      console.log('选择文件时出错', error)
    }
  }

  useEffect(() => {
    ;(async () => {
      // 请求权限
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync()
      if (status !== 'granted') {
        console.log('拒绝访问图片库权限!')
      } else {
        console.log('已经获得访问图片库权限123!')
      }
    })()
  }, [])

  useEffect(() => {
    getCaptcha()
  }, [])

  useEffect(() => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      if (count > 1) {
        setCount(count - 1)
      } else {
        setIsSendEmail(false)
      }
    }, 1000)
    // eslint-disable-next-line
  }, [count])

  useEffect(() => {
    //usernameEl.current.focus()
    //console.log(666, usernameEl.current.isFocused())
  }, [])

  useEffect(() => {
    Api.h5.uploadGetTokenForH5().then(async (res) => {
      if (res.code === 200) {
        await AsyncStorage.setItem('qiniuUploadTokenForH5', res.data.token)
        const qiniuUploadTokenForH5 = await AsyncStorage.getItem(
          'qiniuUploadTokenForH5'
        )
        console.log('qiniuUploadTokenForH5', qiniuUploadTokenForH5)
      }
    })
  }, [])

  return {
    username,
    emailCode,
    isSendEmail,
    count,
    avatar,
    nickname,
    password,
    code,
    visible,
    isLoading,
    captcha,
    visible1,
    usernameEl,
    setEmailCode,
    handleSendEmail,
    setNickname,
    setPassword,
    setCode,
    toggleDialog1,
    handleInput,
    handleLogin,
    handleNav,
    handleVisilbe,
    handleUploadAvatar,
    getCaptcha,
    pickFile,
  }
}

app.json:

{
  "expo": {
    "plugins": [
      [
        "expo-document-picker",
        {
          "iCloudContainerEnvironment": "Production"
        }
      ]
    ]
  }
}

React Native Expo项目上传文件,web前端,react native,react.js,javascript 

 

参考链接:

https://chat.xutongbao.top/

https://docs.expo.dev/versions/latest/sdk/document-picker/

https://blog.csdn.net/xutongbao/article/details/131981469?spm=1001.2014.3001.5501 文章来源地址https://www.toymoban.com/news/detail-616608.html

到了这里,关于React Native Expo项目上传文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Expo项目 使用Native base UI库

    装包: yarn add native-base expo install react-native-svg@12.1.1   Index.js:     参考链接: https://docs.nativebase.io/install-expo https://chat.xutongbao.top/

    2024年02月13日
    浏览(32)
  • React Native 集成到iOS原有的项目上

    集成到现有原生应用 把 React Native 组件集成到 iOS 应用中有如下几个主要步骤: 配置好 React Native 依赖和项目结构。 了解你要集成的 React Native 组件。 使用 CocoaPods,把这些组件以依赖的形式加入到项目中。 创建 js 文件,编写 React Native 组件的 js 代码。 在应用中添加一个RC

    2024年02月12日
    浏览(67)
  • 探索React Native认证实战示例项目:打造安全的移动应用体验

    项目地址:https://gitcode.com/hezhii/react-native-auth-example 在移动开发领域,React Native以其跨平台和高效性能而备受青睐。如果你正在寻找一个直观的、基于React Native的身份验证实现示例,那么这个项目—— react-native-auth-example ,将会是你的理想之选。 react-native-auth-example 是一个简单

    2024年04月27日
    浏览(31)
  • 重启React Native老项目的奇幻之旅:填坑实录与解决方案分享

    这两天为了重启五年前基于 React Native(版本 0.59.9)开发的老项目,经过各种填坑查询等操作,最终把它成功地运行起来了。 在这篇文章中,我将详述那些遭遇的挑战以及对应的解决方案,以期为同样面临此类困境的开发者提供宝贵的经验参考。 这个项目涉及到的环境基本版

    2024年04月16日
    浏览(30)
  • react native 0.73 配置 react-native-fs

    npm yarn android/settings.gradle android/app/build.gradle androidappsrcmainjavacomreactnative_demoMainApplication.kt 把原代码 改为

    2024年04月08日
    浏览(34)
  • 探索React Native的世界:gorhom/react-native-animated-tabbar

    项目地址:https://gitcode.com/gorhom/react-native-animated-tabbar 在移动应用开发领域,React Native以其高效、跨平台的能力受到了广泛的欢迎。今天,我们要向您推荐一个极具创意且实用的React Native组件库——gorhom/react-native-animated-tabbar。它是一个精美设计的动画TabBar,为您的应用提供生

    2024年04月17日
    浏览(57)
  • React与React Native的异同

    开发React一段时间了,一直没有搞清楚React和React Native的差异。今天特意去了解下,发现差异还真不小! 相同点: 1.都是Facebook公司推出的框架。 2.都是基于JSX语言开发的。 差异点: 1、作用的平台不同. 2、工作原理不同. 3、渲染周期不同. 4、组件构成形式不同. 5、宿主平台的

    2024年02月06日
    浏览(32)
  • 维护积极的react native,为什么会有人造谣react native不维护了,停止维护。

            其实近几年我一直关注react -native,他一直更新频繁,0.60大重构,升级了js执行引擎Hermes,当前已经0.70.4版本了。性能越来越提高,但是总感觉到有人在刷百度,只要输入react-native后面就自动提示热搜“react-native 停止维护”,这误导很多人以为真的不维

    2024年02月11日
    浏览(31)
  • 工欲善其事,必先利其器之—react-native-debugger调试react native应用

    调试react应用通常利用chrome的inspector的功能和两个最常用的扩展 1、React Developer Tools (主要用于debug组件结构) 2、Redux DevTools (主要用于debug redux store的数据) 对于react native应用,我们一般就使用react-native-debugger了,它是一个独立的应用,需要单独安装,在mac下可以用如下命令

    2024年02月16日
    浏览(24)
  • React Native 环境安装

    Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.   搭建开发环境 · React Native 中文网 Homebrew(包管理器) → rvm(ruby版本管理) → ruby → cocoapods 安装 Homebrew Homebrew 安装RVM 使用RVM 安装Ruby RVM 查看版本,并设置默认Ruby版本 安装cocoapods pod 生成项目 进入指定目录下

    2024年01月22日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包