夜猫的小站

前端实现粘贴图片并上传

Published on
阅读时间:3分钟408

本文最近一次更新于 1560 个天前,其中的内容很可能已经有所发展或是发生改变。

前言

在网页端写文章时,很多网页都没有直接截图上传图片功能,每次需要在文章中插入图片需要先上传图片再复制图片链接到文章中。找了下文章发现document.onpaste就可以实现。

粘贴图片的基本代码实现

document.onpaste = (ev: ClipboardEvent) => {
    const { clipboardData } = ev;
    if (clipboardData) {
        // 获取复制内容中的数据项
        const { items } = clipboardData; //
        Object.keys(items).forEach((key: string) => {
            const item = items[parseInt(key, 10)];
            if (item.kind === 'file') {
                if (item.type === 'image/png') {
                    const blob = item.getAsFile();
                    let url = window.URL.createObjectURL(blob);
                    // 作为文件上传
                    // var reader = new FileReader();
                    // reader.onload = function(event){
                    // console.log(event.target.result)}; // data url!
                    // reader.readAsDataURL(blob);
                }
            }
        });
    }
};

同理也可以实现文件的快速上传

基于axios的图片上传

document.onpaste = (ev: ClipboardEvent) => {
    const { clipboardData } = ev;
    if (clipboardData) {
        // 获取复制内容中的数据项
        const { items } = clipboardData; //
        Object.keys(items).forEach((key: string) => {
            const item = items[parseInt(key, 10)];
            if (item.kind === 'file') {
                if (item.type === 'image/png') {
                    const blob = item.getAsFile();
                    const formData = new FormData();
                    formData.append('file', blob, 'xxx.png');
                    axios.post('/upload', {
                        data: formData
                    }, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                }
            }
        });
    }
};

基于ajax的图片上传

document.onpaste = (ev: ClipboardEvent) => {
    const { clipboardData } = ev;
    if (clipboardData) {
        // 获取复制内容中的数据项
        const { items } = clipboardData; //
        Object.keys(items).forEach((key: string) => {
            const item = items[parseInt(key, 10)];
            if (item.kind === 'file') {
                if (item.type === 'image/png') {
                    const blob = item.getAsFile();
                    const formData = new FormData();
                    formData.append('file', blob, 'xxx.png');
                    $.ajax({
                        url: '/upload', 
                        type: 'POST',
                        processData: false,    // processData和contentType必须指定为false
                        contentType: false,
                        cache: false,
                        data: formData,
                        success(res) {
                            console.log("上传完成!")
                        }
                    })
                }
            }
        });
    }
};

参考文章

how-does-the-paste-image-from-clipboard-functionality-work-in-gmail-and-google-c