无法从React本机移动应用程序将图像发送到Spring Boot后端

问题描述 投票:0回答:1
  • 我正在尝试从 React Native 移动应用程序将包含图像作为参数之一的 api 请求发送到 Spring Boot 后端,但在后端的图像参数中收到空值
  • 但是当我从邮递员发送相同的 api 请求时,我可以在后端看到图像
export const createGroupApiAction = async (
  createGroupRequestDTO: CreateGroupRequestDTO,
  token: string
): Promise<Group> => {
  // Create a FormData object to handle the file and text data
  const formData = new FormData();

  formData.append('userId', createGroupRequestDTO.userId);
  formData.append('userName', createGroupRequestDTO.userName);
  formData.append('groupName', createGroupRequestDTO.groupName);
  formData.append('groupDescription', createGroupRequestDTO.groupDescription);
  formData.append('isPublic', createGroupRequestDTO.isPublic.toString());
  formData.append('isPaid', createGroupRequestDTO.isPaid.toString());
  formData.append('price', createGroupRequestDTO.price?.toString() || '');

  // If there's an image, convert the image URI to a blob and append it
  if (createGroupRequestDTO.groupImage) {
    const groupImageBlob = await uriToBlob(createGroupRequestDTO.groupImage.uri);
    formData.append('bannerImage', groupImageBlob, 'group-image.png'); // Name and type of the file
  }

  try {
    const response = await axios.post(`${groupBaseUrl}/create`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: `Bearer ${token}`,
      },
    });

    return response.data;
  } catch (error) {
    throw new Error('API request failed: ' + error.message);
  }
};

// Helper function to convert image URI to Blob
const uriToBlob = async (uri: string): Promise<Blob> => {
  const response = await fetch(uri);
  const blob = await response.blob();
  return new File([blob], 'group-image.png', { type: blob.type });
};

弹簧靴

  @PostMapping(value = GroupEndPoints.GroupCrud.CREATE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<NewGroupCreationResponseDTO> createGroup(
            @RequestParam("groupName") String groupName,
            @RequestParam("userId") String userId,
            @RequestParam("userName") String userName,
            @RequestParam("groupDescription") String groupDescription,
            @RequestParam("isPublic", required = false) boolean isPublic,
            @RequestParam("isPaid", required = false) boolean isPaid,
            @RequestParam(value = "price", required = false) Double price,
            @RequestPart(name  = "bannerImage", required = false) MultipartFile bannerImage 
    ) {
        log.info("{} API hit", GroupEndPoints.Base_URL + GroupEndPoints.GroupCrud.CREATE);
}
  • 基本上,我将调试器点放在 log.info() 上,并进行检查,尽管我已从 React Native 端发送图像,但我可以看到 'bannerImage' 为空
  • 但是当我从邮递员向后端发送相同的数据时,我可以在后端看到“bannerImage”

尝试从邮递员向后端发送请求并且成功了

curl --location 'http://localhost:9090/aphrodite/auth/group/create' \
--header 'Authorization: Bearer token' \
--form 'groupName="\"pritam 4\""' \
--form 'bannerImage=@"/C:/Users/Pritam/Downloads/Screenshot 2024-10-17 173738.png"' \
--form 'userId="abc"' \
--form 'userName="ad"' \
--form 'groupDescription="sw"'
  • **我还添加了这个spring boot配置**
 @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
spring-boot react-native expo postman
1个回答
0
投票

如果您使用

fetch(uri)
,由于Android和iOS访问规则,下次尝试访问uri时可能无法访问该图像。因此,请仅在您想将 uri 转换为 Base64 字符串时使用它

顺便说一句,只需像这样转换 blob 就可以了:

const groupImageBlob = {
          uri: createGroupRequestDTO.groupImage.uri
          type: image.mime, // image/png => should be dynamic for other image path
          name: 'group-image.png',
        }

formData.append('bannerImage', groupImageBlob);
© www.soinside.com 2019 - 2024. All rights reserved.