React Native:后端在上传图片时检索 'undefined'

React Native: Backend retrieves 'undefined' when uploading images

我尝试将图像上传到我的后端服务器,但我在 api 调用时出错了。

使用过的包...

"react-native-image-picker": "^4.7.3",
"form-data": "^4.0.0",
"axios": "^0.21.4",
"react-native": "0.67.3"
...
..
.

我从图库中挑选图片的位置:

import {
  launchImageLibrary,
} from 'react-native-image-picker';
import {uploadProfileImages} from '../services/apiService';

export function MyRNApp() {
let image1: any,
    image2: any,
    image3: any,
    image4: any,
    image5: any = null;

launchImageLibrary(options, response => {
              if (response.didCancel) {
                console.log('User cancelled image picker');
              } else if (response.errorCode) {
                console.log('ImagePicker Error: ', response.errorCode);
              } else if (response.assets) {
                  image1 = {
                    uri: response.assets[0].uri,
                    type: response.assets[0].type,
                    name: response.assets[0].fileName,
                  };
                  
                  image2 = {
                    uri: response.assets[1].uri,
                    type: response.assets[1].type,
                    name: response.assets[1].fileName,
                  };
                
                  image3 = {
                    uri: response.assets[2].uri,
                    type: response.assets[2].type,
                    name: response.assets[2].fileName,
                  };
                  image4 = {
                    uri: response.assets[3].uri,
                    type: response.assets[3].type,
                    name: response.assets[3].fileName,
                  };
                  image5 = {
                    uri: response.assets[4].uri,
                    type: response.assets[4].type,
                    name: response.assets[4].fileName,
                  };
              }
            });
const registerComplete = async () => {
      setLoading(true);
      console.log('Before upload: ' + image1);
      await uploadProfileImages(image1, image2, image3, image4, image5)
        .then(async res => {
          console.log('images uploaded...');
          console.log('Result: ', res);
        })
        .finally(() => {
          setLoading(false);
        });
  };

}

我实际的 axios 调用:

import FormData from 'form-data';

export async function uploadProfileImages(
  image1: any,
  image2: any,
  image3: any,
  image4: any,
  image5: any,
): Promise<any> {
  const formData = new FormData();
  formData.append('images', image1);
  formData.append('images', image2);
  formData.append('images', image3);
  formData.append('images', image4);
  formData.append('images', image5);
  return await axios({
    method: 'POST',
    url: `${API_URL}upload`,
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
      Accept: 'application/json',
      'Access-Control-Allow-Origin': '*',
      Authorization: AUTH_HEADER,
    },
  });
}

NestJs 后端:

@Post('upload')
  @HttpCode(200)
  @UseInterceptors(
    FilesInterceptor('images', 5, {
      dest: '../uploads',
      fileFilter: (req, file, cb) => {
        if (file.mimetype.startsWith('image')) {
          cb(null, true);
        } else {
          cb(new Error('No supported filetype'), false);
        }
      },
    }),
  )
  async uploadFile(
    @UploadedFiles() images: Array<Express.Multer.File>,
    @Request() req: any,
  ): Promise<any> {
    if (req.headers['authorization'] === process.env.UPLOAD_KEY) {
      >there it says 'undefined' when making call from RN App 
      console.log('Uploaded files: ' + images[0]);
      return { files: images };
    } else {
      return { status: 'failed' };
    }
  }

后端 API 工作正常(在 Postman 中测试)。 但是当我在 RN 应用程序中进行 api 调用时,似乎不会发送实际照片数据。

我尝试了另一种解决方案,对我有用:

我从图库中选择图片的位置:

export function RNScreen(){
let photo = {
    uri: '',
    type: 'image/jpeg',
    name: 'image.jpg',
  };
launchImageLibrary(options, response => {
              if (response.didCancel) {
                console.log('User cancelled image picker');
              } else if (response.errorCode) {
                console.log('ImagePicker Error: ', response.errorCode);
              } else if (response.assets) {
                photo.uri =
                  Platform.OS === 'android'
                    ? String(response.assets[0].uri)
                    : String(response.assets[0].uri).replace('file://', '');
              }
            });
}

上传进度:


let data = new FormData();
      data.append('images', photo);

      let config = {
        Authorization: AUTH_HEADER,
        'Content-Type': 'multipart/form-data',
      };
      axios.post(API_URL + 'upload', data, {headers: config}).then(response => {
        console.log(response.data);
      });