Last active
May 10, 2024 14:41
-
-
Save yeonhoyoon/1aea02d56e899e5ec43f to your computer and use it in GitHub Desktop.
Send multipart request from javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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