Hello, I’m trying to add profile picture to User in my ‘Edit profile’ page with only one request.
I thought the solution will be similar to “Upload document on entry creation”, but it seems like it isn’t.
So far I’ve with tried with this code:
const handleSubmit = async (e) => {
e.preventDefault();
const data = {};
const formData = new FormData();
[...e.target.elements].forEach(
({ name, type, value, files, ...element }) => {
if (!["submit", "file"].includes(type)) {
data[name] = value;
} else if (type === "file") {
[...files].forEach((file) => {
formData.append(`files.${name}`, file, file.name);
});
}
}
);
formData.append("data", JSON.stringify(data));
const response = await fetch(`http://localhost:1337/api/users/19`, {
headers: {
Authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTcyNTM3NTA2MCwiZXhwIjoxNzI3OTY3MDYwfQ.pBAsMbNg1sswBwh2KSHLt8xKsMzVaxJChkSUmjYiQhE", // Add your token here
},
method: "PUT",
body: formData,
});
const result = await response.json();
console.log(result);
};
return (
<form
onSubmit={handleSubmit}
style={{
display: "flex",
flexDirection: "column",
gap: "1rem",
width: "50%",
margin: "auto",
}}
>
<input type="text" placeholder="username" name="username" />
<input type="file" name="profilePicture" />
<input type="submit" value="Submit" />
</form>
);
The request response is actually 200, but the user info is unchanged.
I’ve double checked the user token and id and they are correct.
I’m aware that it can work with two separated request ‘/api/users/:id’ and ‘/api/upload/’ but I wonder if it is possible to achieve this with just one request?
Any suggestions?