Tartışmalar » Geliştirme

POST binary file to server through GM_xmlhttpRequest.data - convert ArrayBuffer to something usable

§
Gönderildi: 13.10.2019
Düzenlendi: 13.10.2019

POST binary file to server through GM_xmlhttpRequest.data - convert ArrayBuffer to something usable

Please advice, I have initialized var file of File type, and I need to send it's raw content through POST method. This snippet doesn't work, because result isn't added to string as raw sequence of buffer bytes but typename literally. If I understand well, JS string isn't suitable for holding binary data. What I need is to build data var from beginning as binary buffer, adding there everything necessary incl. the ArrayBuffer received as result, and so passing to GM_xmlhttpRequest. Thanks

    .
    .
    var reader = new FileReader();
    var fr = new Promise(function(resolve, reject) {
      reader.onload = function() { resolve(reader.result) }
      reader.readAsArrayBuffer(file);
    });
    fr.then(function(result) {
      const boundary = '----WebKitFormBoundaryTID_GM';
      var data = '--' + boundary + '\r\nContent-Disposition: form-data; name="reqtype"\r\n\r\nfileupload\r\n';
      data += '--' + boundary + '\r\nContent-Disposition: form-data; name="userhash"\r\n\r\n' + userhash + '\r\n';
      data += '--' + boundary + '\r\nContent-Disposition: form-data; name="fileToUpload"; filename="' + file.name + '"\r\n';
      data += 'Content-Type: ' + file.type + '\r\n\r\n';
      data += result + '\r\n--' + boundary + '--\r\n';
      GM_xmlhttpRequest({
        method: 'POST',
        url: 'https://catbox.moe/user/api.php',
        responseType: 'text',
        headers: {
          'Content-Type': 'multipart/form-data; boundary=' + boundary,
          'Content-Length': data.length,
        },
        data: data,
        onload: function(response) {
          if (response.status != 200) reject('Response error ' + response.status);
          resolve(response.response);
        },
        onerror: response => { reject('Response error ' + response.status) },
        ontimeout: function() { reject('Timeout') },
      });
    });
woxxomMod
§
Gönderildi: 13.10.2019
Düzenlendi: 13.10.2019

Simply use FormData API:

GM_xmlhttpRequest({
  method: 'POST',
  url: 'https://catbox.moe/user/api.php',
  data: new FormData({
    reqtype: 'fileupload',
    userhash,
    fileToUpload: result,
  }),
});

So there should be no need to set any headers at all.

§
Gönderildi: 19.01.2020

Thanks!

Cevap paylaş

Yanıt göndermek için oturum açın.