Postingan lainnya
Kelas Premium!
Belajar Javascript untuk website
Gunakan kupon "mulaijs" untuk diskon 75 ribu!
formData.append return null value saat update gambar di reactjs
hi i got a problem when i try to upload an image, the FormData() is return null value inside it, even i already append it
code of uploadhandler
const uploadFileHandler = async (e) => {
const file = e.target.files[0];
const formData = new FormData();
// formData.append("username", "Chris");
formData.append("image", file);
console.log(file);
console.log(formData);
setUploading(true);
try {
const config = {
headers: {
"Content-Type": "multipart/form-data",
},
};
const { data } = await axios.post(
"/api/v1/uploads/primary",
formData,
config
);
setImage(data);
setUploading(false);
} catch (error) {
console.error(error);
setUploading(false);
}};
The file Variable is shown its data but still formData is null and this is the code of form, the user Interface im using React CoreUi Admin and this is the code
<CFormGroup>
<CLabel
htmlFor="images"
style={{ fontWeight: "bold", fontSize: 15 }}
>
Featured Image
</CLabel>
<CInput
style={{ height: "calc(2em + 0.75rem + 2px)" }}
accept="*"
type="file"
id="images"
placeholder="Choose Featured Images"
value={image}
onChange={uploadFileHandler}
/>
{uploading && (
<div className="spinner-border text-primary" role="status">
<span className="sr-only">Loading...</span>
</div>
)}
</CFormGroup>
i have try many method but its still the same, i read a formData.append() documentation still not working. idk where the wrong is
Tanggapan
penggunaan formDatanya sekilas sudah benar. Apakah ada error lain?
ini upload filenya masih gagal si bang, apa mungkin perlu dichomd dulu ya di serverya
1 Jawaban:
<div>ketika browse input type file dikasih event untuk setState file.<br><br>trus pas submit, append nya ambil dari state file.<br><br>contoh referensi, https://stackoverflow.com/questions/62594895/handling-file-uploads-in-reactjs</div>