1. ホーム
  2. javascript

[解決済み] Loading an image to a <img> from <input file>

2022-11-30 09:25:14

Question

I'm trying to load an image selected by the user through an element.

I added a onchange event handler to the input element like this:

<input type="file" name="picField" id="picField" size="24" onchange="preview_2(this);" alt=""/>

and the preview_2 function is:

var outImage ="imagenFondo";
function preview_2(what){
    globalPic = new Image();
    globalPic.onload = function() {
        document.getElementById(outImage).src = globalPic.src;
    }
    globalPic.src=what.value;
}

where outImage has the id value of the tag where I want the new picture to be loaded.

However, it appears that the onload never happens and it does not load anything to the html.

What should I do?

How to solved?

In browsers supporting the File API をサポートしているブラウザでは ファイルリーダー のコンストラクタを使用して、一度ユーザーによって選択されたファイルを読み込むことができます。

document.getElementById('picField').onchange = function (evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;

    // FileReader support
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
            document.getElementById(outImage).src = fr.result;
        }
        fr.readAsDataURL(files[0]);
    }

    // Not supported
    else {
        // fallback -- perhaps submit the input to an iframe and temporarily store
        // them on the server until the user's session ends.
    }
}

ブラウザのサポート

  • IE 10
  • サファリ 6.0.2
  • Chrome 7
  • Firefox 3.6
  • オペラ 12.02

File API がサポートされていない場合、(ほとんどのセキュリティ意識の高いブラウザでは) ファイル入力ボックスからファイルのフル パスを取得したり、データにアクセスしたりすることはできません。 唯一の実行可能なソリューションは、フォームを隠し iframe に送信して、ファイルをサーバーに事前にアップロードさせることです。 次に、そのリクエストが完了したときに、アップロードされたファイルの場所に画像の src を設定できます。