1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【HTML】inputタグのfileでユーザーがアップロードしたファイル情報取得

Last updated at Posted at 2025-05-08

HTML構造

inputタグのfileタイプのhtmlにユーザーが画像アップロード

<input id="uploader" name="fileupload" type="file" />

アップロードしたファイル情報取得

type=fileのinputタグのElementの中のfilesプロパティで取得する

const upload_image = document.getElementById("uploader")
var Fileinput = upload_image.files
console.log(Fileinput)

<input id="uploader" name="fileupload" type="file" accept="image/png, image/jpeg" />

.filesプロパティで返ってくるのはFileListという独自オブジェクト
こいつが結構めんどくさかった

image.png

FileListの構造

●FileListに関するMDNのドキュメントは下記リンク参照
https://developer.mozilla.org/ja/docs/Web/API/FileList
(つーかこっち見た方が早い。。。)

FileListの構造は以下の通り
アップロードしたファイルごとに0,1,2...のようにインデックスが付与
最後にファイルの数を表すlengthプロパティが保持

FileList {
  0: File { name: "file1.jpg", size: ..., type: "image/jpeg", ... },
  1: File { name: "file2.png", size: ..., type: "image/png", ... },
  2: File { name: "file3.pdf", size: ..., type: "application/pdf", ... },
  length: 3
}

例えば、1番目のファイルにアクセスするときは下記

const first_file = upload_image.files[0]
const size = first_file.size //サイズ確認

アップロードされたファイル数を取得する場合は下記

const length = upload_image.files.length

具体的な処理

⭐ユーザーがアップロードしたファイルをforで処理

for (var i = 0; i < files.length; i++) {
 //処理
}

⭐ユーザーがファイルをアップロードしているか検知

        var upload_image = document.getElementById("uploader")
        upload_image.addEventListener("change", (e) => {
            var Fileinput = upload_image.files
            console.log(Fileinput)
            console.log(Fileinput.length)

            if (Fileinput.length >= 1){
             // 処理
            }
         }

image.png
↑ アップロードするとlengthが1になり、ファイルサイズ・ファイル名も取得かのう

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?