Answer the question
In order to leave comments, you need to log in
How to upload photo to server using api?
Making a request to the server using axios
const sendPhoto = async (e) => {
e.preventDefault();
let fd = new FormData();
fd.append("image", file);
let data = await axios.post("http://127.0.0.1:8000/api/post", fd);
return console.log(data.data);
};
$rules = [
'image' => "image"
];
$validator = Validator::make($req->all(), $rules);
if ($validator->fails()) {
return response()->json(['val' => false, 'img' => $req->image]);
}
if (!$req->hasFile('image')) {
return response()->json(['image' => "undefined", 'img' => $req->image]);
}
const data = await fetch("http://127.0.0.1:8000/api/post", {
method: "POST",
body: fd,
});
const res = await data.json()
return console.log(res);
headers: {
"Content-Type": "multipart/form-data",
},
Answer the question
In order to leave comments, you need to log in
But the photo still does not pass validation on the server. I also tried to use instead of FormData:
let formData = new FormData();
formData.append('image', file);
axios.post('http://127.0.0.1:8000/api/post',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
);
if ($request->hasFile('image')) {
$file = $request->file('image');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question