无法使用 React Native / axios 上传文件

问题描述

使用 react-native-image-picker 3.1.1axios,我想将文件从手机上传到服务器。错误信息的缺乏使我无法有效调试。

{"message":"网络错误","name":"错误","config":{"url":"/medias","method":"post","data":{"_parts ":[["file",{"uri":"content://com.mobileapp.imagepickerprovider/cacheDir/rn_image_picker_lib_temp_b50e0844-b2ee-4579-b71d-0a3f2f367e0c.jpg","type":"image/jpeg"," name":"rn_image_picker_lib_temp_b50e0844-b2ee-4579-b71d-0a3f2f367e0c.jpg"}]]},"headers":{"Accept":"application/json,text/plain,/"},"baseURL":"http://192.168.0.14:8000/api","transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfheaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1}}

错误仅在我上传文件时发生。

经过大量搜索,我特别尝试了这个:

  • 上传前将图像置于某种状态
  • 我的 apache 服务器完全没有收到任何信息,我认为数据甚至没有被发送。 当我添加“普通”数据(用于添加数据库中的 json 数据)时,一切正常
  • android:usesCleartextTraffic="true"放入AndroidManifest.xml
  • headers: data.getHeaders()添加 axios 但它不起作用(gerHeaders 不是函数

IndexScreen.js :

...
import * as ImagePicker from 'react-native-image-picker'
import { Context as MediaContext } from '../../../../Context/MediaContext'

const IndexScreen = () => {
  const { newMedia } = useContext(MediaContext)

  return (
    <Button
      title="Select image"
      onPress={() =>
        ImagePicker.launchImageLibrary(
          {
            mediaType: 'photo',includeBase64: false,},(response) => {
            if (response.didCancel) {
              console.log('cancel')
            } else if (response.errorCode) {
              console.log('error')
            } else {
              const data = new FormData()
              data.append('file',{
                uri: response.uri,type: response.type,name: response.fileName
              })

              newMedia(data)
            }
          },)
      }
    />
  )
}

MediaContext.js (这是一个减速器(解释了 dispatch),但我知道我的减速器中一切正常) (上面提到的错误来自这里catch) :

...
const AppApiUpload = axios.create({
  baseURL: 'http://192.168.0.14:8000/api',headers: {
    'Content-Type': 'multipart/form-data'
  }
})

...

const newMedia = (dispatch) => {
  return async (data) => {
    try {
      await AppApiUpload.post('/medias',data)
    } catch (e) {
      console.log(JSON.stringify(e))
    }
  }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)