【问题标题】:React-Native image not uploading using Axios(MultiPart form data) via Content URI (react-native-camera)React-Native 图像未通过 Content URI(react-native-camera)使用 Axios(MultiPart 表单数据)上传
【发布时间】:2022-03-16 20:34:50
【问题描述】:

有以下信息。

React Native 版本 "react-native": "0.63.4"

我正在使用以下库使用设备相机进行图像捕获。

"react-native-camera": "^3.42.2"

import {RNCamera} from 'react-native-camera'

以下是我的功能,从相机捕捉图像时

const onImagePressed = () => {
    const options = {
      title: 'Camera',
      takePhotoButtonTitle: 'Take Photo...',
      mediaType: 'photo',
      quality: 0.5,
      saveToPhotos: true,
    };

    launchCamera(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setImageObject({
          uri: response.uri,
          type: response.type,
          name: response.fileName,
        });
        // blobResponse(response);
      }
    });
  };

对于发布图片或上传图片,我使用 Axios 发布请求和下面提到的表单数据代码。

有效负载示例

const payload = {
      filename: 'test file name',
      type: 'image/jpeg',
      uri: 'content://com.testapp.imagepickerprovider/cacheDir/rn_image_picker_lib_temp_a3c6bd5d-0855-4b57-aa4f-e29fa7676500.jpg',
    };

这与上面提到的从 launchCamera 方法获得的 uri 'content://com.testapp.imagepickerprovider/cacheDir/rn_image_picker_lib_temp_a3c6bd5d-0855-4b57-aa4f-e29fa7676500.jpg' 相同。

表单数据

 var data = new FormData();
    data.append('images', payload);

Axios 请求

export const API_INSTANCE = axios.create({
  baseURL: BASE_URL,
});

上面的函数是一个全局函数,存在于另一个文件中,我只是贴在这里。


await API_INSTANCE.post('/scan/product/save', data, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error.response);
      });

问题是,它将请求发送到服务器,但是当我获得图像密钥时,它变为空或空白。

但同样的事情,我使用邮递员进行了测试,通过放置一个文件然后它会显示数据。

在 Laravel 中进行 API 开发,因此为了更好地了解某人是否在 Laravel 中明确具有与服务器相关的知识,那么他或她也可以查看该代码。

下面是我的 API。

    public function store(Request $request): void
    {
       Log::debug($request->images);
    }

使用上述代码发布时的日志。

[2021-03-12 15:29:32] local.DEBUG:   
[2021-03-12 15:31:48] local.DEBUG:   
[2021-03-12 15:40:03] local.DEBUG:   
[2021-03-12 15:42:45] local.DEBUG:   
[2021-03-12 15:42:47] local.DEBUG:   
[2021-03-12 15:44:12] local.DEBUG:   
[2021-03-12 15:44:35] local.DEBUG:   
[2021-03-12 16:19:24] local.DEBUG:   
[2021-03-12 16:21:19] local.DEBUG:   
[2021-03-12 16:23:03] local.DEBUG:   
[2021-03-12 16:26:20] local.DEBUG:   
[2021-03-12 16:29:58] local.DEBUG:   
[2021-03-12 16:32:29] local.DEBUG:   
[2021-03-12 16:32:53] local.DEBUG:   

使用邮递员发送请求时的日志

[2021-03-12 17:04:53] local.DEBUG: /tmp/phpwgt3X7 

【问题讨论】:

  • 你有没有得到这个排序?我也有同样的问题。

标签: laravel react-native axios


【解决方案1】:

解决上述问题有以下步骤。

  • 使用 Axios 将数据发布到服务器上。
     import axios from 'axios';
     const BASE_URL = '';
     export const API_INSTANCE = axios.create({   baseURL: BASE_URL, });
  • 通过connection.js文件使用上述代码作为应用程序的默认配置。
  • 以下代码用于将数据发送到服务器。
import {API_INSTANCE} from '../config/connection';

 try {
          
      const dataToPost = createFormData(item); //createFormData is custom method
    
      const response = await API_INSTANCE.post(
        '/suburl',
        dataToPost,
      );
    
      if (response.status === 200) {
         //hanlde success case
      } else {
         //hanlde failed case
      }

   } catch (error) {
          
 }

createFormData 定义

const createFormData = (item) => {
    var data = new FormData();
    if (item && item.imageObject && item.imageObject.uri) {

//images are the key that accesses or get from the request input from the server-side.

      data.append('images', {
        name: item.imageObject.name,
        type: item.imageObject.type,
        uri:
          Platform.OS === 'android'
            ? item.imageObject.uri
            : item.imageObject.uri.replace('file://', ''),
      });
      delete item.imageObject;
    }
    //if some of the image object has empty uri then remove it as well.
    if (item && item.imageObject && !item.imageObject.uri) {
      delete item.imageObject;
    }
    //below code to append the all other key/value pair except image object. because we already append above.
    Object.keys(item).forEach((key) => {
      data.append(key, item[key]);
    });

    return data;
  };
  • URI 是在结果中返回的完整路径 launchCamera(由react-native-camera 库提供)方法响应,前面问题部分也提到过(也可以从那里获得帮助)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 2021-01-13
    • 2021-01-29
    • 2021-03-10
    • 2019-10-06
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多