简体   繁体   English

粘贴图像并发送二进制文件

[英]Paste an image and send binary

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.我已经看过这个答案并且效果很好,我唯一的问题是返回 base64 图像。 Is there any way I can alter this code to return image binary?有什么办法可以更改此代码以返回图像二进制文件?

Yes.是的。

Given that item.getAsFile();鉴于item.getAsFile(); already gives you a File object, so you can upload that directly with XMLHttpRequest.send :已经为您提供了File object,因此您可以使用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM