U
U
unclechu2014-06-26 16:04:33
JavaScript
unclechu, 2014-06-26 16:04:33

How to correctly send binary data via XHttpRequest in webkit?

The problem is that in Chromium or Opera there is no sendAsBinary (only send) method on the XHR object. As a result, everything loads correctly in the firelis, and broken files arrive in the lame-legged and crooper, and instead of Unicode characters in the file name - various gibberish.

Code snippet:

self._xhr.open('POST', self.params.url, true);

var boundary = 'xxxxxxxxx';
self._xhr.setRequestHeader('Content-Type', 'multipart/form-data, boundary='+boundary);
self._xhr.setRequestHeader('Cache-Control', 'no-cache');
self._xhr.setRequestHeader('Pragma', 'no-cache');
self._xhr.setRequestHeader('Expires', '0');

var body = '';

// the file
body += '--' + boundary + '\r\n';
body += 'Content-Disposition: form-data; charset: utf-8; accept-charset: utf-8'+
  '; name="'+ self.params.fileFieldName +'"'+
  '; filename="'+ unescape(encodeURIComponent( self.params.file.name )) +'"\r\n';
body += 'Content-Type: application/octet-stream\r\n\r\n';
body += self._reader.result + '\r\n'; // self._reader is instanceof FileReader

// custom data
for (var key in self._toPost) {
  body += '--' + boundary + '\r\n';
  body += 'Content-Disposition: form-data; name="'+ key +'"\r\n';
  body += 'Content-Type: text/plain; charset=utf-8\r\n\r\n';
  body += self._toPost[key].toString() + '\r\n';
}

body += '--' + boundary + '--';

if (self._xhr.sendAsBinary) {
  // firefox
  self._xhr.sendAsBinary(body);
} else {
  // chrome (W3C spec.)
  self._xhr.send(body);
}


How to act in such a situation? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
unclechu, 2014-06-27
@unclechu

Found a solution to an alternative implementation of sendAsBinary .
https://code.google.com/p/chromium/issues/detail?i...

A
Alexander Taratin, 2014-06-26
@Taraflex

html5insight.ru/post/13773171872/working-with-bina...

V
Vitaly Zheltyakov, 2014-06-26
@VitaZheltyakov

Is the title set? There is a line like this in PHPheader("Content-type: text/html; charset=utf-8");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question