I am trying to post an image with some other information through a react form but when I send the request it does not support the type of image file. From postman to my django server it works perfectly but when I try to make post request through react it gives 415 Unsupported media type in dev tools console.
This is the react code
const navigate = useNavigate();
const initialFormData = Object.freeze({
title: "",
place: "",
slug: "",
description: "",
});
const [postData, updateFormData] = useState(initialFormData);
const [postimage, setPostImage] = useState(null);
const handleChange = (e) => {
if ([e.target.name] == 'image') {
setPostImage({
image: e.target.files,
});
console.log(e.target.files);
}
if ([e.target.name] == 'title') {
updateFormData({
...postData,
[e.target.name]: e.target.value.trim(),
['slug']: slugify(e.target.value.trim()),
});
} else {
updateFormData({
...postData,
[e.target.name]: e.target.value.trim(),
});
}
};
const handleSubmit = (e) => {
e.preventDefault();
let formData = new FormData();
formData.append('title', postData.title);
formData.append('slug', postData.slug);
formData.append('author', 10);
formData.append('description', postData.description);
formData.append('place', postData.place);
formData.append('job_date','2022-04-03')
formData.append('image', postimage.image[0]);
axiosInstance.post(`admin/create/`, formData);
navigate({
pathname: '/admin/',
});
window.location.reload();
console.log(postimage.image[0])
};
return (
<Container ponent="main" maxWidth="xs">
<div>
<Typography ponent="h1" variant="h5">
Create New Post
</Typography>
<form noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="title"
label="Post Title"
name="title"
autoComplete="title"
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="place"
label="Job Location:"
name="place"
autoComplete="location"
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker />
</LocalizationProvider>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="description"
label="Description"
name="description"
autoComplete="description"
onChange={handleChange}
multiline
rows={4}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="slug"
label="slug"
name="slug"
autoComplete="slug"
value={postData.slug}
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<input
accept="image/png, image/gif, image/jpeg"
id="image"
onChange={handleChange}
name="image"
type="file"
/>
</Grid>
<Grid item xs={12}>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
onClick={handleSubmit}
>
Create Post
</Button>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
Axios request looks like this with the responsive header:
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
Authorization: localStorage.getItem('access_token')
? 'JWT ' + localStorage.getItem('access_token')
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
I am trying to post an image with some other information through a react form but when I send the request it does not support the type of image file. From postman to my django server it works perfectly but when I try to make post request through react it gives 415 Unsupported media type in dev tools console.
This is the react code
const navigate = useNavigate();
const initialFormData = Object.freeze({
title: "",
place: "",
slug: "",
description: "",
});
const [postData, updateFormData] = useState(initialFormData);
const [postimage, setPostImage] = useState(null);
const handleChange = (e) => {
if ([e.target.name] == 'image') {
setPostImage({
image: e.target.files,
});
console.log(e.target.files);
}
if ([e.target.name] == 'title') {
updateFormData({
...postData,
[e.target.name]: e.target.value.trim(),
['slug']: slugify(e.target.value.trim()),
});
} else {
updateFormData({
...postData,
[e.target.name]: e.target.value.trim(),
});
}
};
const handleSubmit = (e) => {
e.preventDefault();
let formData = new FormData();
formData.append('title', postData.title);
formData.append('slug', postData.slug);
formData.append('author', 10);
formData.append('description', postData.description);
formData.append('place', postData.place);
formData.append('job_date','2022-04-03')
formData.append('image', postimage.image[0]);
axiosInstance.post(`admin/create/`, formData);
navigate({
pathname: '/admin/',
});
window.location.reload();
console.log(postimage.image[0])
};
return (
<Container ponent="main" maxWidth="xs">
<div>
<Typography ponent="h1" variant="h5">
Create New Post
</Typography>
<form noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="title"
label="Post Title"
name="title"
autoComplete="title"
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="place"
label="Job Location:"
name="place"
autoComplete="location"
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker />
</LocalizationProvider>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="description"
label="Description"
name="description"
autoComplete="description"
onChange={handleChange}
multiline
rows={4}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="slug"
label="slug"
name="slug"
autoComplete="slug"
value={postData.slug}
onChange={handleChange}
/>
</Grid>
<Grid item xs={12}>
<input
accept="image/png, image/gif, image/jpeg"
id="image"
onChange={handleChange}
name="image"
type="file"
/>
</Grid>
<Grid item xs={12}>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
onClick={handleSubmit}
>
Create Post
</Button>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
Axios request looks like this with the responsive header:
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
Authorization: localStorage.getItem('access_token')
? 'JWT ' + localStorage.getItem('access_token')
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
Share
Improve this question
edited Mar 8, 2023 at 14:21
Christian Baumann
3,5924 gold badges24 silver badges45 bronze badges
asked Mar 8, 2023 at 13:10
User G AmsterdamUser G Amsterdam
671 silver badge10 bronze badges
2
-
1
You can not perform a file upload with
Content-Type: application/json
. – C3roe Commented Mar 8, 2023 at 13:13 -
if ([e.target.name] == '…')
looks like a mistake, why would you pare an array to a string? Also you should notwindow.location.reload()
if you alreadynavigate(…)
, and certainly you should not do it without waiting for the request to suceed! – Bergi Commented Mar 8, 2023 at 13:31
1 Answer
Reset to default 4As you are uploading the file. You can't use Content-Type: application/json
. You must use Content-Type: multipart/form-data
. You can achieve this with the following axios example.
var formData = new FormData();
formData.append("image", imagefile);
formData.append("title", "test");
formData.append("slug", "test");
axios.post(baseURL, formData, {
timeout: 5000,
headers: {
Authorization: localStorage.getItem('access_token')
? 'JWT ' + localStorage.getItem('access_token')
: null,
'Content-Type': 'multipart/form-data'
accept: 'application/json', // If you receieve JSON response.
}
})