React Native:后端检索“未定义”上传图片时

发布于 2025-01-11 12:24:15 字数 3632 浏览 0 评论 0原文

我尝试将图像上传到后端服务器,但 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 
              

I try to upload images to my backend server, but I'm doing something wrong the api call.

Used Packages...

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

Where I pick the Images from the Gallery:

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);
        });
  };

}

My actuall axios call:

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 Backend:

@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' };
    }
  }

The Backend API works fine (Tested in Postman).
But when I'm making the api call in the RN App, it seems like the actuall photo data will not be send.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长伴 2025-01-18 12:24:15

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

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

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);
      });

I tried a another solution and that works for me:

Where I pick the Image from the Gallery:

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://', '');
              }
            });
}

Upload Progress:


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);
      });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文