Sending an image to REST API
Hi, I'm currently working on a form which sends some data to a backend. Frontend is implemented using Nuxt3, Rest API on the Backend is implemented using Laravel 9.
Firstly I had an issue where the data object would get properly send to the backend but the image property was always empty. I changed it up by sending a FormData object to the backend in the following manner:
const submitHandler = async () => {
const formData = new FormData();
for (const prop in productData.value) formData.append(prop, productData.value[prop]);
const submitResponse = await useFetch(`${config.API_BASE_URL}/products`, {
method: 'POST',
body: formData,
headers: {
Authorization: `Bearer ${userData.token}`,
'Content-Type': 'multipart/form-data',
},
initialCache: false,
async onResponseError({ response }) {
errorStatus.value = response.status;
},
});
};
Now the issue is I'm getting a 302 response code for some reason, and after debugging it seems like it's down to the validate function I'm calling on the request:
public function store(Request $request)
{
$request->validate([
"title" => "required|string",
"initial_price" => "required|integer",
"description" => "string",
"sleeve_condition" => "exists:conditions,id",
"media_condition" => "exists:conditions,id",
"sku" => "string",
"rating" => "integer",
"product_type_id" => "exists:product_types,id",
"author" => "string",
"genre_id" => "exists:genres,id",
"edition" => "string",
"discount_id" => "sometimes|nullable|exists:discounts",
"image" => "required|mimes:image/png,image/jpg,image/jpeg,image/webp|max:10000"
]);
$path = $request->file('image')->store('images', 'public');
return Product::create([$request->all(), "filename" => basename($path), "url" => Storage::disk('public')->url($path)]);
}
Could anyone help me out with this issue? I'm still not 100% sure if it's down to the frontend or backend, I would love to provide more information if needed but I'm not sure what more to attach
Please or to participate in this conversation.