I'm working on a project where I need to paste an image and it will upload to my server. I've seen this answer and it works great, my only issue is that is returns a base64 image. Is there any way I can alter this code to return image binary?
Asked
Active
Viewed 162 times
1 Answers
1
Yes.
Given that item.getAsFile();
already gives you a File
object, so you can upload that directly with XMLHttpRequest.send
:
document.addEventListener( 'paste', onPaste );
function onPaste( ev ) {
const items = ( ev.clipboardData || ev.originalEvent.clipboardData ).items;
for( const item of items ) {
if( item.kind === 'file' ) {
const file = item.getAsFile();
uploadFileUsingXhr( file );
}
}
}
function uploadFileUsingXhr( file ) {
const xhr = new XMLHttpRequest();
xhr.open( 'POST', '/your-upload-handler', /*async:*/ true );
xhr.send( file );
// TODO: xhr.upload.progress reporting
}

Dai
- 141,631
- 28
- 261
- 374