php 带有表单数据的 Ajax 文件上传 Laravel 5.3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41820805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:28:34  来源:igfitidea点击:

Ajax File Upload With Form Data Laravel 5.3

phpajaxlaravelfile-uploadlaravel-5.3

提问by Mr Robot

i want to upload a profile imageof a userto the server and i'm stuck at ajax upload of image

我想配置文件上传imageuser服务器,我停留在图像的阿贾克斯上传

all my form data are posting to databaseincluding the image namebut the file is not uploading to the server

我所有的表单数据都发布到database包括image name但文件没有上传到服务器

my view is

我的观点是

//form
<form id="example-form" method="post" enctype="multipart/form-data">
    {!! csrf_field() !!}
    <div class="row">
        <div class="col m12">
            <div class="row">
                <div class="input-field col m12 s12">
                    <input id="name" name="name" type="text" placeholder="Full Name" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="email" name="email" type="email" placeholder="Email" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="phone_number" name="phone_number" type="tel" placeholder="Phone Number" class="required validate">
                </div>                                                        
                <div class="input-field col m6 s12">
                    <input id="address" name="address_city_village" type="text" placeholder="Address City Village">
                </div>
                <div class="input-field col m6 s12">
                    <input id="state" name="address_state" type="text" placeholder="State">
                </div>                                                        
                <div class="input-field col s12">
                    <input id="password" name="password" type="password" placeholder="Password" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="confirm" name="confirm" type="password" placeholder="Confirm Password" class="required validate">
                </div>
                <div class="file-field input-field col s12">
                    <div class="btn teal lighten-1">
                        <span>Image</span>
                        <input type="file" name="image">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" >
                    </div>
                </div>                                                        
            </div>
        </div>
    </div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="waves-effect waves-green btn blue">Submit</button>
</div>
</form>

//ajax
$(document).on("click", ".agent-add", function () {

    var agent_id = $(this).data('id');

    $('form').submit(function(event) {
        event.preventDefault();
        $.ajax
        ({
            url: '{{ url('/agents') }}',
            type: 'POST',              
            data: {
                "_method": 'POST',
                "name": $('input[name=name]').val(),
                "email": $('input[name=email]').val(),
                "phone_number": $('input[name=phone_number]').val(),
                "address_city_village": $('input[name=address_city_village]').val(),
                "address_state": $('input[name=address_state]').val(),
                "image": $('input[name=image]').val(),
                "password": $('input[name=password]').val()
            },
            success: function(result)
            {
                location.reload();
            },
            error: function(data)
            {
                console.log(data);
            }
        });

    });
}); 

my controller is

我的控制器是

public function store(Request $request)
{
    if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
       return $this->respondBadRequest('Phone Number Exists');
    }
    else 
    {
        User::create($request->all());

        return redirect('agents')->with('Success', 'Agent Added');

        if($request->hasFile('image')) {
            $file = $request->file('image');

            //you also need to keep file extension as well
            $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

            //using array instead of object
            $image['filePath'] = $name;
            $file->move(public_path().'/uploads/', $name);

        }
    }
}

i guess i'm missing something in ajax posting, but i couldn't figure it out

我想我错过了一些东西ajax posting,但我想不通

i dd($request->all());

一世 dd($request->all());

the result is

结果是

array:9 [▼
  "_token" => "heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM"
  "name" => "fwe"
  "email" => "[email protected]"
  "phone_number" => "4444422555"
  "address_city_village" => "sgf"
  "address_state" => "gfdgsdf"
  "password" => "ffffff"
  "confirm" => "ffffff"
  "image" => UploadedFile {#208 ▼
    -test: false
    -originalName: "Screenshot (8).png"
    -mimeType: "image/png"
    -size: 135920
    -error: 0
    path: "C:\wamp\tmp"
    filename: "php47F2.tmp"
    basename: "php47F2.tmp"
    pathname: "C:\wamp\tmp\php47F2.tmp"
    extension: "tmp"
    realPath: "C:\wamp\tmp\php47F2.tmp"
    aTime: 2017-01-24 06:14:40
    mTime: 2017-01-24 06:14:40
    cTime: 2017-01-24 06:14:40
    inode: 0
    size: 135920
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\wamp\tmp\php47F2.tmp"
  }
]

i checked the C:\wamp\tmp\php47F2.tmpenen there i din't find the image

我在C:\wamp\tmp\php47F2.tmp那里检查了enen 我没有找到图像

looking forward for much needed help

期待得到急需的帮助

thank you

谢谢你

回答by Jaymin Panchal

Try using the FormDatain ajaxwhile you upload a file.

FormDataajax上传文件时尝试使用in 。

Just try this

试试这个

$('form').submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: '{{ url('/agents') }}',
        type: 'POST',              
        data: formData,
        success: function(result)
        {
            location.reload();
        },
        error: function(data)
        {
            console.log(data);
        }
    });

});

OR

或者

You can try with this jQuerylibrary

你可以试试这个 jQuerylibrary

https://github.com/malsup/form

https://github.com/malsup/form

EDIT

编辑

public function store(Request $request)
{
    if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
       return $this->respondBadRequest('Phone Number Exists');
    }
    else 
    {
        $user=User::create($request->all());

        if($request->hasFile('image')) {
           $file = $request->file('image');

           //you also need to keep file extension as well
           $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

           //using the array instead of object
           $image['filePath'] = $name;
           $file->move(public_path().'/uploads/', $name);
           $user->image= public_path().'/uploads/'. $name;
           $user->save();
        }
        return redirect('agents')->with('Success', 'Agent Added');
    }
}

回答by Mayank Pandeyz

Try something like this:

尝试这样的事情:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'route_url',
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
    });

回答by Andrew

Just me or does your <input type="file">not have a "name" attribute? Therefore the server is not receive the file data from the post?

只有我还是您<input type="file">没有“名称”属性?因此服务器没有收到来自post的文件数据?

EDIT:

编辑:

After you insert the record into the database, you then handle the file uploading - but you never then update the record with the files name.

将记录插入数据库后,您将处理文件上传 - 但您永远不会使用文件名更新记录。

*Just confirm that the file was uploaded.

*只需确认文件已上传。

回答by Sidra

name attribute not set for the file type input. May be?

未为文件类型输入设置名称属性。或许?

回答by namal

I will explain using a simple example.

我将用一个简单的例子来解释。

HTML:

HTML:

<form id="header_image_frm" method="POST" action="">
    <input type="file" name="header_image" id="header_image" value="Upload Header Image">
</form>

JS: (Properties of ajax called contentType, processData must)

JS:(ajax的属性叫contentType,processData必须)

<script>
  $(document).ready(function() {
    $('#header_image').change(function() {
        let formData = new FormData($('#header_image_frm')[0]);
        let file = $('input[type=file]')[0].files[0];
        formData.append('file', file, file.name);
        $.ajax({
            url: '{{ url("/post/upload_header") }}',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type: 'POST',   
            contentType: false,
            processData: false,   
            cache: false,        
            data: formData,
            success: function(data) {
                console.log(data);
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
  });
</script>

Laravel / PHP:

Laravel / PHP:

public function upload(Request $request) {
  if ($_FILES['file']['name']) {
    if (!$_FILES['file']['error']) {
        $name = md5(rand(100, 200));
        $ext = explode('.', $_FILES['file']['name']);
        $filename = $name . '.' . $ext[1];
        $destination = public_path() . '/images/' . $filename;
        $location = $_FILES["file"]["tmp_name"];
        move_uploaded_file($location, $destination);
        echo '/images/' . $filename;
    } else {
        echo = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
    }
  }
}