

upload上传文件类型的限制的几种方式(element)_JavaScript_lo_InfoQ写作平台
source link: https://xie.infoq.cn/article/3a90238435996874c5197d748
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.

upload 上传文件类型的限制的几种方式(element)
在上传文件过程中,设计需求上这边总是需要对上传文件进行限制和判断,避免用户的盲操作,导致上传文件类型不对后,无法得到正确的信息,造成不好的体验影响,所以在页面上我们需要对文件类型做判断
这里我们采用的是 element 的 upload 上传组件做例子,大多数上传组件类似,这里就不一一举例了,
我们这次是对图片类型做限制
首先我们使用组件
<el-upload
accept="image/*"
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:before-upload="beforeAvatarUpload"
</el-upload>
accept 属性只能与 配合使用。它规定能够通过文件上传进行提交的文件类型。
我们从 element 官网可以看到对文件上传前的钩子是 before-upload
通过文件类型判断
在大多数文件中,在文件 file 属性中,有 type 属性,所以我们可以根据 type 属性进行判断
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
return isJPG;
}
通过文件名称判断
但是仍然有少数文件是没有 type 类型的,我曾经就碰到过,不知道是系统的原因,还是文件自身的缘故,我们我们需要第二道判断方法,进行限制
这里就是文件名后缀了,无论是 windows 还是 mac os,文件都有相应的后缀名
beforeUpload(file) {
const typeArry = ['.jpg', '.png', '.bmp', '.JPG', '.PNG', '.BMP', '.gif', '.GIF'];
const type = file.name.substring(file.name.lastIndexOf('.'));
const isImage = typeArry.indexOf(type) > -1;
if (!isImage) {
this.$message.error('上传文件必须为图片');
}
return isCSV;
},
通过读取文件的二进制数据来判断文件类型
以上,两种方式可以解决绝大多数的文件,但是总是存在个别顽固分子,既没有 type,也没有文件名后缀,或者是其他因素,无法进而判断的,
所以我们可以通过读取文件的二进制数据来借以判断文件类型
在这篇文章中,也有详细的说明如何做Antd Upload单个图片的校验和上传?
主要是通过魔数来判断。 PNG 的魔数是 0x89 50 4E 47 0D 0A 1A 0A,我们可以通过读取文件二进制的前 8 个字节来一一比对来判定文件的类型:
常见的图片魔数
JPEG (jpg),文件头:FFD8FF
PNG (png),文件头:89504E47
GIF (gif),文件头:47494638
TIFF (tif),文件头:49492A00
const getBuffers = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file.slice(0, 8));
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
})
};
Recommend
-
41
严正声明:本文仅限于技术讨论,严禁用于其他用途。 简介 文件上传漏洞是web安全中经常利用到的一种漏洞形式。一些web应用程序中允许上传图片,文本或者其他资源到指定的位置,文件上传漏洞就是利用这些可以上传...
-
18
前言 vue-element-admin自带上传图片组件,在使用的过程中发现上传速度很慢,尤其是上传一些大图需要耗时几十秒不能忍受。出现这种情况,是因为upload组件会将图片上传到 action="https://httpbin.org/post" ,...
-
13
Vue+element-ui文件上传阿里云oss+预览word 、excel、ppt、pdf、png、jpg ...
-
13
by zhangxinxu from http://www.zhangxinxu.com 本文地址:http://www.zhangxinxu.com/wordpress/?p=342...
-
7
Vue el-upload 文件上传封装 Vue el-upload 文件上传封装 Published on Aug 24, 2021 in 前端 with
-
5
为了绕过阿里云盘上传文件类型限制,一种将压缩包改变成一张图片的方式分享 2021-09-13 技术
-
8
用 nginx-upload-module 模块实现往服务器上传文件的时候,文件名会变成一串数字。这是 nginx-upload-module 模块为了避免文件冲突,做了一个 file hashing。 1. 关于 file hashing 先...
-
6
el-upload上传文件公司和学校项目都用到了上传文件的功能,记录一下。 express实现的上传接口const express = require('express'); // 文件上传模块 const multiparty = require...
-
10
文件上传漏洞靶场(作者前言)
-
10
基于vue+Element UI的文件上传(可拖拽上传) 精选 原创
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK