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);
}
尝试从邮递员向后端发送请求并且成功了
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"'
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
如果您使用
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);