File upload and js fetch()

408 views
Skip to first unread message

Fabs

unread,
Mar 7, 2018, 1:27:38 AM3/7/18
to Fat-Free Framework
Hi All,

I'm fairly new to f3, got most of what I need sorted but I'm having issues uploading files with a JS fetch promise.

I can run my code with a normal POST but I need to stay on the same page rather than being brought back to my original one.

F3/PHP code:
function uploadImages() {
$w3 = new Web();
$overwrite = true;
$slug = true;

$files = $w3->receive(function($file,$formFieldName){
                   
            //var_dump($file); I can see this with synch POST
                   
             if($file['size'] > (2 * 1024 * 1024)) // if bigger than 2 MB
                  return false; // this file is not valid, return false will skip moving it

             return true;
 }, $overwrite, $slug);

 //var_dump($files); I can see this with synch POST
}

But when I call the function with an asynch call, using fetch().then().catch() I can't seem to find any info about the file I just posted.

I've tried
file_get_contents('php://input')
$this->f3->get('BODY');
$this->f3->get('POST');
$this->f3->get('FILES');
but they are all empty.

Note that the data in the browser console looks OK, this is part of the JS code:

          var frmData = new FormData(event.target);
       
        for (var key of frmData.keys()) {

            lData[key] = frmData.get(key)

        }

        console.log(lData);

        var    init     = {
                        method:       'POST',
                        body:           JSON.stringify(lData),
                        headers:      new Headers({'Content-Type': 'application/json'}),
                        mode:           'cors',
                        credentials: 'same-origin'
                      };
       
        fetch(lUrl, init)
        .then(res         => res.json())
        .then(function(response) {
            //console.log(response);
              if(response.status != 'error') {
                  return response;
              }
              var error = new Error();
              error.response = response;
              throw error;
        })
        .then(function(response) {
            console.log(response);
              divE.html(response['message']);
              divE.addClass("alert alert-success");
              divI.innerHTML = lData.file.name;
              image_name.value = lData.file.name;
        })
        .catch(function(error) {
            console.log(error);
              divE.html(error['response']['message']);
              divE.addClass("alert alert-danger");
        });

lData is OK, so the data seems to get sent the PHP function, response is OK so the PHP function does not raise any exception (but does not move the files either).

Any idea of what I'm doing wrong?

Cheers,
Fabs.

ikkez

unread,
Mar 7, 2018, 4:35:48 AM3/7/18
to f3-fra...@googlegroups.com
A POST request with a Content-Type application/json is likely to cause trouble for uploads in PHP. The file contents should be in the BODY var in such a case, but since it's binary data, perhaps the webserver is crushing it and I think $web->receive would not handle it.

Try to use POST + Content-Type: application/x-www-form-urlencoded
or PUT + Content-Type of the file mime-type, or try "binary/octet-stream" or leave it blank

and use Web->receive() just as usual. Just notice that the callback attribute $formFieldName is not available for PUT-uploads

Fabs

unread,
Mar 7, 2018, 5:56:43 PM3/7/18
to Fat-Free Framework
Thanks ikkez.

I'd tried all of them yesterday before posting to the group but have had no luck.
Then I though to use the FAL plugin to read/move the file "manually" (programmatically) but I think I'm gonna go with a normal form post targeting an iFrame, will let you know.

Thanks again.

Fabs

unread,
Mar 7, 2018, 6:19:09 PM3/7/18
to Fat-Free Framework
It works just fine.

Thanks again for your help.
Reply all
Reply to author
Forward
0 new messages