N
N
Nikita Stechkin2021-02-11 22:35:27
React
Nikita Stechkin, 2021-02-11 22:35:27

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);
  };


And I process it on the server

$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]);
     }


The validator throws an error saying that I'm not passing a photo, but a string, hasFile also returns false. I tried changing axios to fetch
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);


But the photo still does not pass validation on the server. I also tried to use instead of FormData:
headers: {
        "Content-Type": "multipart/form-data",
      },


But that didn't help me either.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alvvi, 2021-02-12
@VAMPIRE37

But the photo still does not pass validation on the server. I also tried to use instead of FormData:

Why instead? Both are needed.
Correct request:
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'
      }
    }
 );

On back:
if ($request->hasFile('image')) {
  $file = $request->file('image');
}

Well, validation should also work, whether it's an image rule or a file rule.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question