Ajax File Upload With Form Data Laravel 5.3

后端 未结 5 1740
迷失自我
迷失自我 2020-12-28 21:48

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

all my form data are posting to datab

相关标签:
5条回答
  • 2020-12-28 22:20

    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?

    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.

    0 讨论(0)
  • 2020-12-28 22:25

    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
                    }
             });
        });
    
    0 讨论(0)
  • 2020-12-28 22:26

    I will explain using a simple example.

    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)

    <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'];
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-28 22:36

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

    0 讨论(0)
  • 2020-12-28 22:44

    Try using the FormData in ajax while you upload a file.

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

    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');
        }
    }
    
    0 讨论(0)
提交回复
热议问题