I'm trying to send an image and two text fields to the express server, but it gives the error "Multipart: Boundary not found".
const handleFileUpload = async () => {
if (!selectedFile) {
Alert.alert('Ошибка', 'Выберите файл для загрузки');
return;
}
const formData = new FormData();
formData.append('image', {
uri: selectedFile.uri,
type: selectedFile.type,
name: selectedFile.fileName || 'image.png',
});
formData.append('title', newImageTitleFile);
formData.append('description', newImageDescriptionFile);
try {
const response = await fetch('http://localhost:5000/api/images/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Ошибка загрузки файла');
}
const data = await response.json();
console.log('Загружено:', data);
} catch (error) {
console.error('Ошибка:', error);
}
};
I tried to remove the header 'Content-Type': 'multipart/form-data', nothing changes.
The fetch function should send the formData object as multipart/form-data now that it contains a file. Take a look at the developer tools in your browser and look for the request. You should be able to see both the header Content-Type
that described the boundary and the body with the boundary string separating each key/value.
You cannot send the files as a object (with the {}
). You give the file (selectedFile.files[0]
) as the value for the image data.
It is not clear from you question what the back-end expects, but this example (like your own code) will just do the multipart/form-data request.
const handleFileUpload = async(e) => {
e.preventDefault();
let form = e.target;
if (!form.selectedFile.files[0]) {
alert('Ошибка', 'Выберите файл для загрузки');
return;
}
const formData = new FormData();
formData.append('image', form.selectedFile.files[0]);
formData.append('title', form.newImageTitleFile.value);
formData.append('description', form.newImageDescriptionFile.value);
try {
const response = await fetch('/api/images/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Ошибка загрузки файла');
}
const data = await response.json();
console.log('Загружено:', data);
} catch (error) {
console.error('Ошибка:', error);
}
};
document.forms.form01.addEventListener('submit', handleFileUpload);
<form name="form01">
<input type="file" name="selectedFile">
<input type="text" name="newImageTitleFile">
<input type="text" name="newImageDescriptionFile">
<button>Submit</button>
</form>