E
E
Erouech2020-09-20 16:38:35
JavaScript
Erouech, 2020-09-20 16:38:35

Uploading images from camera to server?

Good afternoon, there was such an interesting problem. When loading an existing image into the form, and sending it to the server, everything works fine.
But when loading a picture just taken from the phone (something like: select file > take a picture > ok) Everything does not go according to plan.
If you do not create an instance of the \Image class , then the php method sees the files, but if I create it, then it suddenly does not see them.
\Image - Intervention Image ( image.intervention.io )
Here is the method that accepts a photo from the form

public function updatePhoto(Request $request){
    if ($request->hasFile('photo')) {
      Log::info('file exist: '.\Auth::id());
    }else{
      Log::info('file not exist: '.\Auth::id());
    }
    
    $img = \Image::make($request->file('photo'));
    // ...

Here is the form
<input id="updatePhotoFile" type="file" accept="image/*" style="display:none">
<div class="recoverLink" id="update-photo">Изменить фото</div>

And finally the script that sends the photo to the server
updatePhoto = function(photo){
    let xhr = new XMLHttpRequest();
    let data = new FormData();
    data.append("photo", photo);
    xhr.open('POST', '/ajax/update-photo', false);
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
    xhr.send(data);
    if (xhr.status != 200) {
      return xhr.status + ': ' + xhr.statusText;
      alert('err')
    } else {
      return xhr.responseText;
    }
}

$( "#update-photo" ).on( "click", function() {
    $( "#updatePhotoFile" ).trigger( "click" );
});

$('#updatePhotoFile').change(function() {
    let photo;
    if(photo = updatePhotoFile.files[0]){
    let result = JSON.parse(updatePhoto(photo)); // post ajax 
        console.log(result)
    }
});


[2020-09-20 13:18:27] production.INFO: file exist: 58  // PC
[2020-09-20 13:18:51] production.INFO: file exist: 58  // PHONE - не создавая экземпляр \Image
[2020-09-20 13:19:10] production.INFO: file not exist: 58  // PHONE - Создавая экземпляр \Image


Who faced similar, I ask to help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2020-09-20
@zkrvndm

After attaching the photo, look at what is in the input on the client side, if some parameters are missing or the photo has a zero size. If at first glance everything is in order, try sending the form not with Ajax, but in the usual way. Even if this does not help, then I see two solutions in the forehead: send the file as a string or pack it first into a zip archive before sending it and send the archive itself. To generate an archive on the browser side, you can use the JSZip plugin, it will give you a Blob that can already be safely sent to the server with Ajax.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question