0

I have an issue on Laravel 5.5 get ajax file.I can receive the file by $_FILES,but the $request->file() cant. Here's the code.

Html & Ajax are as below:

<html>
    <form id="testForm">
        <input type="file" id="pic" name="pic">
        <button type="submit">upload</button>
    </form>
</html>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#testForm").submit(function (event) {
        event.preventDefault();
        $.ajax({
             type: "post",
             url: "http://localhost/yhy-admin/public/index.php/admin_api/upload",
             data: new FormData($(this)[0]),
             processData: false,
             contentType: false,
             cache: false,
             success: function (res) {
             console.log(res);
        }
    });
  });
</script>

Controller :

public function upload(Request $request)
    {
        $data["content"]["pic"] = $request->pic;
        $data["content"]["pic_file"] = $_FILES;
        $data["content"]["all"] = $request->all();
        return $data;
    }

response,as u see,only the $_FILES cant get the file:

{
        "content":{
            "pic":[],
            "pic_file":
                {
                    "pic":{
                    "name":"TIM\u56fe\u724720180105101806.jpg",
                   "type":"image\/jpeg",
       "tmp_name":"G:\\Users\\Administrator\\AppData\\Local\\Temp\\php9F4.tmp",
                   "error":0,
                   "size":107085
                }
             },
             "all":{"pic":[]}
        }
    }
Aftab H.
  • 1,493
  • 4
  • 12
  • 25
xin liang
  • 1
  • 1

2 Answers2

0

add in form tag enctype="multipart/form-data"

Karan
  • 1,106
  • 1
  • 7
  • 22
0

I soveld it. Simply write as this:

public function upload(Request $request)
    {
        $file = null;
        if ($request->file("pic")->isValid()) {
            $file = $request->file("pic")->store("/");
        }
        $data["content"] = $file;

        return $data;
    }
xin liang
  • 1
  • 1