Вот мой клиентский код отправки изображений
Код: Выделить всё
const pickImage = async () => {
const result = await launchImageLibrary({
mediaType: 'photo',
quality: 1,
selectionLimit: 1,
includeBase64: true,
});
if (!result.didCancel && result.assets) {
setImageUri(result.assets[0].uri);
console.log('result.assets[0].base64', result.assets[0].uri);
const base64Image = result.assets[0].base64;
if (base64Image) {
const totalChunks = Math.ceil(base64Image.length / CHUNK_SIZE);
// const imageBuffer = Buffer.from(result.assets[0].base64, 'base64');
for (let i = 0; i < totalChunks; i++) {
const start = i * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, base64Image.length);
const chunk = base64Image.substring(start, end);
const data = {
index: i,
totalChunks: totalChunks,
imageData: chunk,
};
client.send(
Buffer.from(JSON.stringify(data)),
undefined,
undefined,
8888,
ipAddress,
error => {
if (error) {
Alert.alert('Something Went Wrong!', error.message);
} else {
console.log(
`Chunk ${i + 1}/${totalChunks} sent successfully to IP:`,
ipAddress,
);
}
},
);
}
}
}
};
Код: Выделить всё
const startServer = async () => {
server.on('error', err => {
console.log(`Socket error: ${err}`);
});
const receivedChunks: any = [];
server.on('message', async (msg, rinfo) => {
let message = JSON.parse(msg);
const {index, totalChunks, imageData} = JSON.parse(msg.toString());
if (index && totalChunks && imageData) {
receivedChunks[index] = imageData;
if (receivedChunks.length === totalChunks) {
const completeImage = receivedChunks.join('');
try {
// Save the complete image
const imagePath = `${RNFS.DocumentDirectoryPath}/receivedImage.png`;
await RNFS.writeFile(imagePath, completeImage, 'base64')
.then(async () => {
const fileExists = await RNFS.exists(imagePath);
if (fileExists) {
setExactScore(prevScore => {
const updatedScore = {...prevScore};
updatedScore.player1Image = `file://${imagePath}`;
return updatedScore;
});
} else {
console.error('File not found after saving.');
}
})
.catch(err => console.error('Error saving image:', err));
} catch (error) {
console.error('Error saving image:', error);
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... e-udp-data