V
V
Vitaly Balayan2019-02-16 23:49:03
JavaScript
Vitaly Balayan, 2019-02-16 23:49:03

Why doesn't ajax send the file?

I upload a file to the site, after which it should immediately be processed by the JS function, with an ajax request

function selectLocalImage() {
    var input = document.createElement("input");
    input.setAttribute("type", "file");
    input.click();
    // Listen upload local image and save to server
    input.onchange = () => {
        const file = input.files[0];
        // file type is only image.
        if (/^image\//.test(file.type)) {
            this.saveToServer(file, "image");
        } else {
            console.warn("Only images can be uploaded here.");
        }
    };
}

function saveToServer(file) {
  console.log('обрабатываем');
  var uploadFile = file;
  var image = new FormData(uploadFile);

  console.log(image);
    // Upload file to server and get the uploaded file url in response then call insertToEditor(url) after getting the url from server
  $.ajax({
    type: 'post',
    url: '/images/upload',
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    data: {
      file: image,
    },
    processData: false,
    	contentType: false,
    success: function(response){ // What to do if we succeed
      console.log('у тебя все получилось');
      $('#result').html(response);
      // console.log(response);
    },
    error: function(response){
      alert('Error'+response);
    }
  });
}

function insertToEditor(url) {
    // push image url to editor.
    const range = quill.getSelection();
    quill.insertEmbed(range.index, "image", url);
}


URL will inject on the controller

public function upload(Request $request)
  {
    $file = $request->all();
    dd($file);
    // $path = $file->store('uploads', 'public');
    // $link = '/storage/uploads/'.$path;

    // return response()->json(['url' => $link]);
  }


But in response I get just - []

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2019-02-17
@Sanasol

FormData: https://developer.mozilla.org/en-US/docs/Web/API/F...
https://stackoverflow.com/a/23981045

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question