Laravel 5.2 send form data to controller using ajax

I try to write a script that send image data to the controller and save it, I get the image using jQuery, then I create the form data and send it with ajax, but in the controller my index is undefined, I try to save the image with $_FILES, my code is: my ajax script :

var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var title_image = $('#questionTitleImage').prop('files')[0];
var form_data = new FormData();
form_data.append('file', title_image);
$('#addQuestionLoader').show();
$.ajax({
    url: '/imageUpload/',
    type: 'GET',
    data: form_data,
    contentType: false,
    processData: false,
    success: function (data) {
        console.log(data);
    },
    complete:function () {
        $('#addQuestionLoader').hide();
    }
});

And my controller:

public function imageUpload(Request $request) {
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    } else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }
}

Please help me complete my project, if you have a better way to save the image using ajax, please help me.

+4
source share
1 answer

, . , - :

var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var title_image = $('#questionTitleImage').prop('files')[0];

var xhr = new XMLHttpRequest();
if (xhr.upload) {
    formData.append('file', title_image);
    // you forgot including the token
    formData.append('_token', CSRF_TOKEN);
    // change your request to POST, GET is not good for files
    xhr.open("POST", '/imageUpload', true);
    xhr.send(formData);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert("Uploaded");
        }
    }
}

javascript, .

, move_uploaded_file, , , Laravel Intervention.

http://image.intervention.io/

- , , !

:

use Illuminate\Http\Request;
use Intervention\Image\ImageManager;

public function upload(Request $request)
{
    // get image
    $file = $request->file('file');

    // instantiate Intervention Image
    $imageManager = new ImageManager();
    $image = $imageManager->make($file);

    // save image with a new name
    $image->save(public_path() . '/img/new-image.jpg', 100);

    return response()->json([
        'success' => true,
    ]);
}

, Laravel:

// get image
$file = $request->file('file');
// save it
$file->store('img');

, , , :)

EDIT:

// javascript
$('body').on('change', '#questionTitleImage', function(e){
    e.stopPropagation();
    e.preventDefault();

    var CSRF_TOKEN = $('input[name=_token]').val();
    var files = e.target.files || e.dataTransfer.files;
    var file = files[0];

    var xhr = new XMLHttpRequest();
    if (xhr.upload) {
        var formData = new FormData();
        formData.append('file', file);
        formData.append('_token', CSRF_TOKEN);
        xhr.open("POST", '/image', true);
        xhr.send(formData);

        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert('Success');
            }
        }
    }
});

CSRF:

// this goes below your input type file
{{ csrf_field() }}

formdata :

formData.append('_token', $('input[name=_token]').val());
+1

Source: https://habr.com/ru/post/1663595/


All Articles