一、标签及属性
<input>type 类型为 file 的 input 元素使得用户可以选择一个或多个元素以提交表单的方式上传到服务器上,或者通过 Javascript 的 File API 对文件进行操作 .
1.value
- 选择文件的路径
- 没有选择文件该值为空字符串
- 为了阻止恶意软件猜测文件路径, 该值 以
C:\fakepath\为前缀
2.multiple
- 多个文件可以被同时选中,如果不希望多选, 忽略multiple属性
3.accept
- 限制允许的文件类型
- accept 属性接受一个逗号分隔的 MIME 类型字符串
- 一个有效的 MIME 类型,但没有扩展名
accept="image/png"或accept=".png"— 只接受 png 图片.accept="image/png, image/jpeg"或accept=".png, .jpg, .jpeg"— PNG/JPEG 文件accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"— 接受任何 MS Doc 文件类型.audio/*表示所有音频文件video/*表示所有视频文件image/*表示所有图片文件
二、样式
第一种方法: 通过定位+透明度来实现(不推荐)
样式代码相对较多,并且对于cursor,file的按钮不会应用样式,所以需要让他宽度更宽才行,这样就会出现在不可见区域也能点击上传的bug(目前没找到解决办法)。
<!--html结构--><!--第一种方法:通过定位+透明度来实现(不推荐)--><div class="first"><button>上传图片</button><input type="file"></div>
.first{
position: relative;
height: 30px;
line-height: 30px;
}
.first button,.first input{
position: absolute;
left: 85px;
top: 0;
width: 100px;
height: 30px;
color: #fff;
background-color: skyblue;
border-radius: 5px;
border: none;
outline: none;
cursor: pointer;
}
.first input{
opacity: 0;
width: 185px;
left: 0;/*这里是为了让cursor效果在按钮内完全生效,但是弊端就是宽度增加,在按钮左侧看不见的位置也能点击到*/
}
第二种方法:通过label的关联属性来实现
局限性:限制了元素,只能使用label,且只能使用id来进行关联,id作为唯一标识,页面上定义的id越少越好,想要在同一页面使用多个就需要定义多个id
<div class="item">
<label for="file1">上传图片</label>
<input type="file" id="file1">
</div>
.item label{
display: inline-block;
width: 100px;
height: 30px;
text-align: center;
color: #fff;
line-height: 30px;
background-color: skyblue;
border-radius: 5px;
cursor: pointer;
}
.item input{
display: none;
}
第三种方法:通过js事件绑定来实现(推荐)
<div class="item">
<button class="btn">上传图片</button>
<input type="file" id="file">
</div>
.item button{
width: 100px;
height: 30px;
color: #fff;
background-color: skyblue;
border-radius: 5px;
border: none;
outline: none;
cursor: pointer;
}
.item input{
display: none;
}
document.querySelector('.btn').addEventListener('click',function () {
document.querySelector('#file').click();
});
三、FileList
1.files
- 含了许多
File文件的列表对象- 每个 File 对象包含了下列信息:
name: 文件名.lastModified: UNIX timestamp 形式的最后修改时间.lastModifiedDate:Date形式的最后修改时间.size: 文件的字节大小.空文件为0type: 文件的 MIME 类型.
四、实例
1、图片上传(formData)
let limitTypes = ['image/png','image/jpg','image/jpeg','image/gif']
let limitMaxSize = 100 * 1024;
fileInp.onchange = async function(){
let file = fileInp.files[0];
if(!file) return;
if(!limitTypes.includes(file.type)) {
alert('必须是xxx格式');
fileInp.value = "";
return;
}
if(limitMaxSize < file.size){
alert('最大只能上传100kb');
fileInp.value = "";
return;
}
let formData = new FormData();
//Content-type: mutilpart/form-data
formData.append('chunk',file);
/** 1.文件名是否可重复?
* 2.文件名是否需要编码?可以交给后端做
* 3.传多份文件时是否可重复?
*/
formData.append('fileName',$formatFileName(file.name).fileName);
let result = await $ajax({
url: 'http://127.0.0.1:8080/single',
data:formData,
progress: ev => {
//ev.loaded 已经上传大小
//ev.total total总文件大小
_data.total = Math.cell(ev.loaded/ev.total*100);
}
});
if(result.code == 0){
console.log('...')
}
}
function $formatFileName(fileName){
let dotIndex = fileName.lastIndexOf('.'),
name = fileName.subString(0,dotIndex),
suffix = fileName.subString(dotIndex+1);
// 有超低概率重复可以加上用户id
name = md5(name) + new Date().getTime();
return {
hash:name,
suffix,
fileName:`${name}.${suffix}`
}
}
2、图片上传(Base64)
let limitTypes = ['image/png','image/jpg','image/jpeg','image/gif']
let limitMaxSize = 100 * 1024;
let _data = new Proxy({
total:0
},{
set(target,key,value){
target[key] = value;
if(_data.total>=100){
progress.innerHTML = '上传成功';
return;
}
progress.innerHTML = `${_data.total}%`;
}
});
fileInp.onchange = async function(){
let file = fileInp.files[0];
if(!file) return;
if(!limitTypes.includes(file.type)) {
alert('必须是xxx格式');
fileInp.value = "";
return;
}
if(limitMaxSize < file.size){
alert('最大只能上传100kb');
fileInp.value = "";
return;
}
let base64 = await convertBase64(file)
// 为了防止base64为乱码,使用encodeURIComponent编码
base64 = encodeURIComponent(base64)
let result = await $ajax({
url: 'http://127.0.0.1:8080/single',
header:{
'Content-Type':'application/www-form-urlencode'
},
data:`chunk=${base64}&filename=${$formatFileName(file.name).fileName}`
});
if(result.code == 0){
console.log('...')
}
}
function convertBase64(file){
return new Promise(resolve=>{
let fileRead = new FileRead();
fileRead.readAsDataURL(file);
fileRead.onload = ev => {
resolve(ev.target.result)
}
});
}
function $formatFileName(fileName){
let dotIndex = fileName.lastIndexOf('.'),
name = fileName.subString(0,dotIndex),
suffix = fileName.subString(dotIndex+1);
// 有超低概率重复可以加上用户id
name = md5(name) + new Date().getTime();
return {
hash:name,
suffix,
fileName:`${name}.${suffix}`
}
}
3、大文件上传

let limitTypes = ['image/png','image/jpg','image/jpeg','image/gif']
let limitMaxSize = 100 * 1024 * 1024;
let _data = new Proxy({
total:0
},{
set(target,key,value){
target[key] = value;
if(_data.total>=100){
progress.innerHTML = '上传成功';
return;
}
progress.innerHTML = `${_data.total}%`;
}
});
fileInp.onchange = async function(){
let file = fileInp.files[0];
if(!file) return;
progress.innerHTML = "0%"
if(!limitTypes.includes(file.type)) {
alert('必须是xxx格式');
fileInp.value = "";
return;
}
if(limitMaxSize < file.size){
alert('最大只能上传100mb');
fileInp.value = "";
return;
}
let partSize = file.size / 5,
cur = 0,
i = 0,
partList = [];
let { hash, suffix, fileName } = $formatFileName(file.name)
while(i < 5){
partList.push({
chunk: file.slice(cur,cur+partSize),
filename: `${hash}-${i}.${suffix}`
});
i++;
cur+=partSize;
}
//并发切片请求
partList.map(item => {
let formData = new FormData();
formData. (item.chunk);
formData.append(item.filename);
return $ajax({
url: 'http://127.0.0.1:8080/chunk',
data:formData
}).then(result => {
if(result.code == 0){
_data.total+=20;
return Promise.resolve(result);
}
return Promise.reject(result);
});
});
//合并切片
await Promise.all(partList)
let result = await $ajax({
url: 'http://127.0.0.1:8080/merge',
header:{
'Content-Type':'application/www-form-urlencode'
},
data:`${fileName}`
});
if(result.code == 0){
console.log('...')
}
}
function $formatFileName(fileName){
let dotIndex = fileName.lastIndexOf('.'),
name = fileName.subString(0,dotIndex),
suffix = fileName.subString(dotIndex+1);
// 有超低概率重复可以加上用户id
name = md5(name) + new Date().getTime();
return {
hash:name,
suffix,
fileName:`${name}.${suffix}`
}
}
五、预留问题
- 附件暂停上传
- 附件取消上传
