Skip to content

Instantly share code, notes, and snippets.

@yeonhoyoon
Last active May 10, 2024 14:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yeonhoyoon/1aea02d56e899e5ec43f to your computer and use it in GitHub Desktop.
Save yeonhoyoon/1aea02d56e899e5ec43f to your computer and use it in GitHub Desktop.
Send multipart request from javascript
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes));
};
}
function sendMultiPartReqeust(filename, mimeType, imageData, message) {
var boundary = '----ThisIsTheBoundary1234567890';
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
formData += imageData;
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.onload = xhr.onerror = function() {
console.log(xhr.responseText);
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr.sendAsBinary(formData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment