簡體   English   中英

Ajax 文件上傳與表單數據 Laravel 5.3

[英]Ajax File Upload With Form Data Laravel 5.3

我想將user的個人資料image上傳到服務器,但我卡在 ajax 上傳圖片

我所有的表單數據都發布到database ,包括image name ,但文件沒有上傳到服務器

我的看法是

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

    });
}); 

我的 controller 是

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

        }
    }
}

我想我在ajax posting中遺漏了一些東西,但我想不通

dd($request->all());

結果是

array:9 [▼
  "_token" => "heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM"
  "name" => "fwe"
  "email" => "sanjiarya2112@gmail.com"
  "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"
  }
]

我檢查了C:\wamp\tmp\php47F2.tmp enen 我找不到圖像

期待急需的幫助

謝謝你

在上傳文件時嘗試在ajax使用FormData

試試這個

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

});

或者

你可以試試這個jQuery library

https://github.com/malsup/form

編輯

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

嘗試這樣的事情:

$('#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
                }
         });
    });

只有我還是您的<input type="file">沒有“名稱”屬性? 因此服務器沒有收到來自post的文件數據?

編輯:

將記錄插入數據庫后,您將處理文件上傳 - 但您永遠不會使用文件名更新記錄。

*只需確認文件已上傳。

未為文件類型輸入設置name屬性。 也許?

我將用一個簡單的例子來解釋。

HTML:

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

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:

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'];
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM