基本上传
<div ref="drag">
<input type="file" name="file" @change="handleFileChange"/>
</div>
data() {
return {
file: null
}
}
method: {
async blobToString (blob) {
return new Promise(resolve => {
const reader= new FileReader()
reader.onload = function () {
const ret = reader.result.split('') // 拆分成数组
.map(v => v.charCodeAt()) // 转成unicode吗
.map(v => v.toString(16).toUpperCase()) // 转成16进制
.map(v => v.padStart(2, '0')) // es2017新增 padStart()用于头部补全,padEnd()用于尾部补全
.join('') // 拼接成字符串
resolve(ret)
}
reader.readAsBinaryString(blob)
})
},
async isImage(file) {
// file: File {name: "backiee-177377.jpg", lastModified: 1599795969245, lastModifiedDate: Fri Sep 11 2020 11:46:09 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 1534215, …}
const ret = await this.blobToString(file.slice(0, 6)) // Blob {size: 6, type: ""}
const isGif = (ret == '47 49 46 38 39 61') || (ret == '47 49 46 38 37 61')
return isGif;
},
bindEvents() {
const drag = this.$ref.drag
drag.addEventListener('dragover', e => {
drag.style.borderColor = 'red'
e.preventDefault()
})
drag.addEventListener('dragleave', e => {
drag.style.borderColor = '#eee'
e.preventDefault()
})
drag.addEventListener('drag', e => {
drag.style.borderColor = '#eee'
e.preventDefault()
const fileList = e.dataTransfer.file
this.file = fileList[0]
})
},
async unloadFile() {
if (!this.isImage(this.file)) {
console.log("不合规则")
return
}
const form = new FormDate();
form.append('name', 'file');
form.append('file', this.file);
const ret = await this.$http.post('/upoadfile', form, {
onUploadProgress: progress => {
this.uploadProgress = Number(((progress.loaded / progress.total)*100).toFixed(e))
}
})
},
handleFileChange(e){
const [file] = e.target.files
if (!file) return
this.file = file
}
}
- 通过dom的监听函数 监听dragover, dragleave 来设置拖拽进来后的hover态样式
- 通过drap 来获取上传状态
- 通过axios的onUploadProgress 来获取上传进度
- 通过文件流的16进制头信息的前6组来判断是什么类型
https://www.cnblogs.com/ppazhang/archive/2012/11/07/2759097.html
3.PNG
- 文件头标识 (8 bytes) 89 50 4E 47 0D 0A 1A 0A
4.GIF
- 文件头标识 (6 bytes) 47 49 46 38 39(37) 61
G I F 8 9 (7) a
- padStart padEnd
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
- Gif判断前6个, PNG判断前8个,PDF 255044 前3个
JPG:
- 文件头标识 (2 bytes): FF, D8(SOI) (JPEG 文件标识)
- 文件结束标识 (2 bytes): FF, D9 (EOI)
网友评论