You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native图片上传技术问询:权限申请与FormData配置

如何在React Native中实现带权限校验的相册/相机图片上传功能?

一、依赖准备

先安装常用的图片选择库和权限处理库:

# 安装图片选择库
npm install react-native-image-picker
# 安装权限处理库
npm install react-native-permissions

注意:iOS需执行pod install完成依赖安装,RN 0.60+版本Android无需手动配置链接

二、配置系统权限

iOS(Info.plist)

在项目的Info.plist文件中添加权限描述:

<key>NSCameraUsageDescription</key>
<string>需要访问相机拍摄图片</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问相册选择图片</string>

Android(AndroidManifest.xml)

在AndroidManifest.xml中添加对应权限:

<!-- 相机权限 -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Android 13+ 相册访问权限 -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<!-- Android 12及以下 相册读写权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" />

三、权限校验与申请

在调用相机/相册前,先检查并申请对应权限:

import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { Platform } from 'react-native';

// 检查相机权限
const checkCameraPermission = async () => {
  const permission = Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA;
  const result = await check(permission);
  if (result === RESULTS.GRANTED) return true;
  
  const requestResult = await request(permission);
  return requestResult === RESULTS.GRANTED;
};

// 检查相册权限
const checkPhotoPermission = async () => {
  const permission = Platform.OS === 'ios' 
    ? PERMISSIONS.IOS.PHOTO_LIBRARY 
    : (Platform.Version >= 33 ? PERMISSIONS.ANDROID.READ_MEDIA_IMAGES : PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE);
  const result = await check(permission);
  if (result === RESULTS.GRANTED) return true;
  
  const requestResult = await request(permission);
  return requestResult === RESULTS.GRANTED;
};

四、调用相机/相册选择图片

使用react-native-image-picker获取图片资源:

import { launchCameraAsync, launchImageLibraryAsync, MediaTypeOptions } from 'react-native-image-picker';

// 打开相机拍摄
const openCamera = async () => {
  const hasPermission = await checkCameraPermission();
  if (!hasPermission) {
    alert('相机权限未授权,无法使用相机');
    return;
  }
  const result = await launchCameraAsync({
    mediaType: MediaTypeOptions.Images,
    allowsEditing: true,
    quality: 0.8,
  });
  if (!result.canceled) {
    const file = result.assets[0];
    await uploadImage(file.uri, file.fileName, file.type);
  }
};

// 打开相册选择图片
const openGallery = async () => {
  const hasPermission = await checkPhotoPermission();
  if (!hasPermission) {
    alert('相册权限未授权,无法选择图片');
    return;
  }
  const result = await launchImageLibraryAsync({
    mediaType: MediaTypeOptions.Images,
    allowsEditing: true,
    quality: 0.8,
  });
  if (!result.canceled) {
    const file = result.assets[0];
    await uploadImage(file.uri, file.fileName, file.type);
  }
};

五、构造FormData并上传图片

按照需求构造FormData并发起上传请求:

const uploadImage = async (uri, fileName, fileType) => {
  // 适配Android uri格式(部分设备返回的uri需去除file://前缀)
  const file_parse_uri = Platform.OS === 'android' ? uri.replace('file://', '') : uri;
  const file_parse_name = fileName || `image_${Date.now()}.jpg`;

  // 构造FormData
  const data = new FormData();
  data.append("file", {
    uri: file_parse_uri,
    type: fileType || "image/jpeg",
    name: file_parse_name,
  });

  // 配置请求头
  const headers = {
    Authorization: 'Bearer your_auth_token', // 按需添加授权token
    "Content-Type": "multipart/form-data",
  };

  try {
    const response = await fetch('https://your-upload-api-domain.com/upload', {
      method: 'POST',
      headers,
      body: data,
    });
    const resData = await response.json();
    console.log('上传成功:', resData);
    alert('图片上传完成');
  } catch (error) {
    console.error('上传失败:', error);
    alert('图片上传失败,请稍后重试');
  }
};

注意事项

  • Android 13+ 必须使用READ_MEDIA_IMAGES权限,旧版本依赖READ_EXTERNAL_STORAGE
  • iOS若需将拍摄图片保存到相册,需额外配置NSPhotoLibraryAddUsageDescription权限
  • 部分Android设备返回的图片uri带有file://前缀,必须去除才能正常上传

内容的提问来源于stack exchange,提问作者backenddev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:55:29