Laravel5.5无法上传ajax文件

时间:2018-01-05 10:08:05

标签: javascript php jquery ajax laravel-5

我在Laravel 5.5上有一个问题是获取ajax文件。我可以通过$ _FILES接收文件,但$ request->文件()不能。 这是代码。

Html& Ajax如下:

<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>

控制器:

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

响应,正如您所见,只有$ _FILES无法获取文件:

{
        "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":[]}
        }
    }

2 个答案:

答案 0 :(得分:0)

添加表格标签enctype =&#34; multipart / form-data&#34;

答案 1 :(得分:0)

我很喜欢它。 只需写下:

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

        return $data;
    }