35

检查上传文件的大小

 3 years ago
source link: https://www.itwork.club/2020/12/18/check-file-size/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

检查上传文件的大小

漂洋过海来看你

IT俱乐部-码出人生

检查上传文件的大小

Dec 18, 2020JavaScript6点击

我们可以通过 js 检查用户上传的文件是否过大


通过 file 类型的 input 可以得到用户上传的文件,也就是一个 File 对象

通常情况下, File 对象是来自用户在一个 元素上选择文件后返回的 FileList 对象,也可以是来自由拖放操作生成的 DataTransfer 对象,或者来自 HTMLCanvasElement 上的 mozGetAsFile() API。在Gecko中,特权代码可以创建代表任何本地文件的File对象,而无需用户交互(有关详细信息,请参阅 注意事项

file 有一个 size 属性

以字节为单位返回文件的大小。

检查文件是否过大,可以写成

1
2
3
4
5
6
7
export const checkFileSizeTooLarge = (file, limitSize) => {
if (!(file instanceof File)) {
throw new Error('Not a file')
}
const size = Math.round(file.size / 1024)
return size > limitSize
}

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2020/12/18/check-file-size/

版权声明: 转载请注明出处

qrcode.jpg

体验小程序「简易记账」

qrcode_mp.jpg

关注公众号「特想学英语」


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK