I'm beginner I try to upload an image.jpg with React using Laravel , it work with Postman but with React js dose not work and throws a message error : FormToAddFile.jsx:17
POST http://127.0.0.1:8000/api/storefile 422 (Unprocessable Content)
here is my codes :
React form :
import React from "react";
import { useRef } from "react"
import axiosClient from "../../../axios-client";
export default function FormToAddFile(){
const fileValue=useRef();
const nameValue=useRef();
const descriptionValue=useRef();
const SaveFile=()=>{
const payload={
image:fileValue.current.value,
name:nameValue.current.value,
description:descriptionValue.current.value,
}
console.log("tosave",payload)
axiosClient.post("/storefile",payload,{headers:{'Content-Type':"multipart/form-data"}},).then(({data})=>{
console.log(data)
}).catch((err)=>{
console.log(err)
})
}
return (
<div className="w-fit mt-4">
<form action="" className="grid grid-cols-1 gap-4 overflow-x-hidden " >
<input ref={nameValue} type="text" placeholder="File Name" className="py-2 pl-2 focus:outline-none text-black font-semibold"/>
<textarea ref={descriptionValue} placeholder="Description" name="" id="" className="resize-none py-2 pl-2 focus:outline-none text-black font-semibold"></textarea>
<label htmlFor="inputfile " className="bg-cyan-600">
<input ref={fileValue} id="inputfile" type="file" className="savefilelabel" />
</label>
<button onClick={SaveFile} className="savefile">Save File</button>
</form>
</div>
)
}
my controller:
public function store(FilesStoreRequest $request)
{
try {
$imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
// Create Product
File::create([
'name' => $request->name,
'image' => $imageName,
'description' => $request->description
]);
// Save Image in Storage folder
Storage::disk('public')->put($imageName, file_get_contents($request->image));
// Return Json Response
return response()->json([
'message' => "Product successfully created."
],200);
} catch (\Exception $e) {
// Return Json Response
return response()->json([
'message' => "Something went really wrong!"
],500);
}
}
**it's working with Postman but not with my React form **
The reason is that you used general json
data. To upload file, you must use FormData
object because the backend expects a multipart/form-data
. I will provide updated code.
import React from "react";
import { useRef } from "react"
import axiosClient from "../../../axios-client";
export default function FormToAddFile(){
const fileValue=useRef();
const nameValue=useRef();
const descriptionValue=useRef();
const SaveFile=()=>{
// Create FormData object and append necessary information.
const formData = new FormData();
formData.append('image', fileValue.current.files[0]);
formData.append('name', nameValue.current.value);
formData.append('description', descriptionValue.current.value);
console.log("tosave", formData);
axiosClient.post("/storefile", formData, {headers:{'Content-Type':"multipart/form-data"}},).then(({data})=>{
console.log(data)
}).catch((err)=>{
console.log(err)
})
}
return (
<div className="w-fit mt-4">
<form action="" className="grid grid-cols-1 gap-4 overflow-x-hidden " >
<input ref={nameValue} type="text" placeholder="File Name" className="py-2 pl-2 focus:outline-none text-black font-semibold"/>
<textarea ref={descriptionValue} placeholder="Description" name="" id="" className="resize-none py-2 pl-2 focus:outline-none text-black font-semibold"></textarea>
<label htmlFor="inputfile " className="bg-cyan-600">
<input ref={fileValue} id="inputfile" type="file" className="savefilelabel" />
</label>
<button onClick={SaveFile} className="savefile">Save File</button>
</form>
</div>
)
}