LoginSignup
0
1

【JavaScript】画像などのファイルをCtrl+Vで貼り付けたり、ドラッグ&ドロップで貼り付けたりする方法

Last updated at Posted at 2024-06-22

結論

  • MIMEタイプは画像で絞っているため、カスタムしたい場合は変えてください。
  • ファイルが複数渡されたときはMIMEタイプが一致した最初のファイルのみを対象にしているため、複数処理したい場合は書き換えてください。
  • ドロップ先のDOMは各自書き換えてください。今は画面のどこでもドロップ可能になっています。
(() => {
    let isLoading = false;

    window.addEventListener("paste", e => {
        e.preventDefault();

        if (isLoading) {
            return;
        }
        isLoading = true;
        
        let imageItem = null;
        for (const item of e.clipboardData.items) {
            // MINEタイプの確認
            if (item.type.startsWith("image/")) {
                imageItem = item;
                break;
            }
        }
        if (imageItem === null) {
            isLoading = false;
            return;
        }

        const imageFile = imageItem.getAsFile();
        const url = URL.createObjectURL(imageFile);
        const image = new Image();
        image.onload = () => {
            // 画像の読み込み完了
            // TODO:あなたがimageを使ってやりたい処理を書く
            URL.revokeObjectURL(url);
            isLoading = false;
        };
        image.onerror = () => {
            // 画像の読み込み失敗
            URL.revokeObjectURL(url);
            isLoading = false;
        };
        image.src = url;
    }, false);

    window.addEventListener("dragover", e => {
        e.preventDefault();
    }, false);

    window.addEventListener("drop", e => {
        e.preventDefault();

        if (isLoading) {
            return;
        }
        isLoading = true;

        let imageFile = null;
        for (const file of e.dataTransfer.files) {
            // MINEタイプの確認
            if (file.type.startsWith("image/")) {
                imageFile = file;
                break;
            }
        }
        if (imageFile === null) {
            isLoading = false;
            return;
        }

        const reader = new FileReader();
        reader.onload = e => {
            const image = new Image();
            image.onload = () => {
                // 画像の読み込み完了
                // TODO:あなたがimageを使ってやりたい処理を書く
                isLoading = false;
            };
            image.onerror = () => {
                // 画像の読み込み失敗
                image = null;
                isLoading = false;
            };
            image.src = e.target.result;
        }
        reader.onerror = () => {
            // 画像の読み込み失敗
            isLoading = false;
        };
        reader.readAsDataURL(imageFile);
    });
})();
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1