question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support FormData / multipart requests

See original GitHub issue

Is it somehow possible to use multipart forms in Tabris.js 2 beta2? Either via Fetch API or XMLHttpRequest?

For the following code snippet:

let formData = new FormData();
formData.append('content', new Blob(content));

… I get the exception:

Reference Error: Can’t find variable: FormData

tia Cheers Sascha

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
jokorivaicommented, Jun 9, 2019

Thank you @mpost for added this to the milestone. While we are waiting, as I am, here is my sample app demonstrating uploading files to server. PHP and NodeJS server code samples are included.

https://github.com/jokorivai/tabrisjs-upload-file

XMLHttpRequest is used:

function uploadFile(fileUri, cbDone, cbProgress){
    // NodeJS:
    let url = 'http://yourserver:808/v1/upload/image';
    // PHP:
    // let url = 'http://yourserver/test-post.php';

  let options = {
    fileKey : 'uploadImage',
    mimeType : 'image/jpg',
    fileName : fileUri.substr(fileUri.lastIndexOf('/') + 1),
    fileExt : fileUri.substr(fileUri.lastIndexOf('.') + 1),
    headers : {
      dummy: 'dummy'
    }
  }
  fs.readFile(fileUri).then(function(buffer){
    let oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.setRequestHeader('Content-Type', 'application/octet-stream');
    oReq.setRequestHeader('params', JSON.stringify(options));
    oReq.onload = function (oEvent) {
      console.log(oEvent.target.$responseData);
      let data = oEvent.target;
      let res = JSON.parse(data.$responseData);
      let uploadResult = {
        fileName: res.result.fileName, 
        responseCode: data.$status, 
        bytesSent: res.result.size,
        result: res.result
      };
      (cbProgress||function(a,b,c){})(100, 100);
      (cbDone||(function(x,y, z){}))(false, uploadResult);            
    };
    oReq.ontimeout= function(){
      (cbDone||(function(x,y,z){}))({error: 'Request timeout'}, null);
    };
    oReq.onabort = function(){
      (cbDone||(function(x,y,z){}))({error: 'Request aborted'}, null);
    };
    oReq.onprogress = function(evt){
      if (evt.lengthComputable) {
        (cbProgress||function(a,b,c){})(evt.total, evt.loaded);
      } else {
        (cbProgress||function(a,b,c){})(100, 60);
      }
    };
    oReq.send(buffer);
  }).catch(function(e){
    (cbDone||(function(x,y,z){}))(e, null);
  });
}

NodeJS code:

const server = express();
server
  .post('/v1/upload/image', function(rq, rs){
    let data = [];
    let params;
    if (rq.headers['params']==''){
      params = {
        fileKey: 'uploadImage',
        mimeType : 'image/jpeg',
        fileExt: 'jpg',
        fileName: 
          'img-'+cripto.createHmac('sha256', 'uploadImage'+Math.radom()).update('upl'+Math.random()).digest('hex')+
          '-'+Math.random()+
          '.jpg',
        headers : {
          
        }
      }
    } else {
      params = JSON.parse(rq.headers['params']);
      params.fileName = 
        'img-'+cripto.createHmac('sha256', params.fileName+Math.random()).update('upl'+Math.random()).digest('hex')+
        '-'+Math.random()+'.'+
        params.fileExt
    }
    rq.on('data', function(chunk){
      data.push(chunk);
    });
    rq.on('end', function(chunk){      
      let buffer = Buffer.concat(data);
      let fname = './'+FILE_STORAGE+'/'+params.fileName;
      let writer = fs.createWriteStream(fname);
      writer.on('open', function(f){
        writer.write(buffer, function(e){
          if (e){
            console.log(e);
            rs.end(JSON.stringify({error: true, msg: 'File upload failed'}));
          }
          else {
            let fileUri = 'http://'+_SERVER_DOMAIN+'/filestorage/'+params.fileName;
            let resObj = {error: false, result: {
              fileName: params.fileName,
              filePath: fname,
              fileUri: fileUri,
              size: buffer.length,
              msg: "File uploaded\nRetrieve this file by GET "+fileUri
              }
            };
            // console.log(resObj);
            rs.end(JSON.stringify(resObj));
          }
        });
      });
    });
  })
;

PHP simple code:

$postdata = file_get_contents("php://input");
$dir = 'filestorage';
$file_name = "file".rand() .".jpg"; 
if (!is_dir(__DIR__.'/'.$dir)){
  mkdir(__DIR__.'/'.$dir);
}
$fp = fopen(__DIR__.'/'.$dir .'/'.$file_name, "wb");
fwrite($fp, $postdata);
fclose($fp);
$response = array(
  'error'=>false,
  'result' => array(
    'fileName' => $file_name,
    'filePath' => __DIR__.'/'.$dir.'/'.$file_name,
    'fileUri'  => 'http://'.$_SERVER['SERVER_NAME'].'/'.$dir.'/'.$file_name,
    'size'     => filesize(__DIR__.'/'.$dir.'/'.$file_name),
    'msg'      =>'File uploaded\nRetrieve this file by GET http://'.$_SERVER['SERVER_NAME'].'/'.$dir.'/'.$file_name
  )
);

echo json_encode($response);
1reaction
ralfstxcommented, Sep 11, 2017

Apparently, all available modules build either on browser APIs or on Node APIs. None of them just assembles the multipart message.

I guess we’d have to implement FormData for Tabris.js to support multipart requests.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using FormData Objects - Web APIs | MDN
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest . It is primarily intended for use in...
Read more >
Multipart Requests - Swagger
Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file...
Read more >
How to send a "multipart/form-data" with requests in python?
If you specify both files and data , then it depends on the value of data what will be used to create the...
Read more >
Sending HTTP requests, understanding multipart/form-data
How to make HTTP requests in pure Node.js with streams. Uploading files using multipart/form-data and how this format works.
Read more >
Sending Request for Ticket creation using MultiPart Form data ...
A multipart form-post is an HTTP request sent using an HTML form, submitted with enctype set to "multipart/form-data". The request body is ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found