iT邦幫忙

0

【JavaScript】File 計算單位要用 1000 bytes 還是 1024 bytes?

7514 2022-11-26 00:20:091826 瀏覽
  • 分享至 

  • xImage
  •  

前言

當使用者從瀏覽器上傳檔案後,可以取得修改時間、檔案名稱、檔案大小...相關的資訊如下:

  • lastModified
    Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).
  • name
    Returns the name of the file referenced by the File object.
  • webkitRelativePath
    Returns the path the URL of the File is relative to.
  • size
    Returns the size of the file in bytes.
  • type
    Returns the MIME type of the file.
// 單一檔案
const File = () => {
    const [file, setFile] = useState({});
    console.log("file: ", file);
    return (
        <input type="file" multiple onChange={evt => setFile(evt.target.files[0])} />
    )
}; 
// 多個檔案在 `<input>` 加上 multiple
const File = () => {
    const [fileList, setFileList] = useState([]);
    if (fileList) {
        for (const file of fileList) {
            console.log("file: ", file);
        }
    }
    return (
        <input type="file" multiple onChange={evt => setFile(evt.target.files)} />
    )
};

取得 file size 後,這該如何計算呢

搜尋資料時會看到 1GB = 1000 bytes,也有一說是 1024 bytes。

電腦相關的單位是二進制,因此一直是 1 Kilobyte = 1024 bytes,1 Megabyte = 1024 kilobytes,1 Gigabyte = 1024 megabytes,然而 "kilo" 意思是 "千" 的意思,也就代表 1000,就慢慢轉變為 1 Kilobyte = 1000 byte...

在 1998 年由國際電工委員會(IEC)訂定新的單位,用來取代過去的舊單位,因而有了 1 Kibibyte (KiB) = 1024 bytes, 1 Mebibyte (MiB) = 1024 KiB, 1 Gibibyte(GiB) = 1024 MiB,但在長期的使用習慣下,大部分的人可能還是會有 1KB = 1024 bytes 的誤解。

十進位(SI) 單位(bytes)
1 Kilobyte(KB) 1000 B
1 Megabyte(MB) 1000 KB
1 Gigabyte(GB) 1000 MB
二進位(IEC) 單位(bytes)
1 Kibibyte(KiB) 1024 B
1 Mebibyte(MiB) 1024 KiB
1 Gibibyte(GiB) 1024 MiB

而 Mac 和 Windows 系統的檔案計算單位,分別是用 1000 bytes 和 1024 bytes,因此像是雲端儲存空間,就會需要針對不同的裝置有不同的計算單位,簡單且詳細的說明可以參考此部影片

參考來源:
https://developer.mozilla.org/en-US/docs/Web/API/File
https://www.quora.com/Is-1-GB-equal-to-1024-MB-or-1000-MB
https://zh.wikipedia.org/zh-tw/Mebibyte


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言