Ajax File Upload With Form Data Laravel 5.3

后端 未结 5 1758
迷失自我
迷失自我 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:26

    I will explain using a simple example.

    HTML:

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

    
    

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

提交回复
热议问题