Skip to content

Instantly share code, notes, and snippets.

@yeonhoyoon

yeonhoyoon/multipart.js

Last active Jan 8, 2021
Embed
What would you like to do?
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