daily-share
daily-share copied to clipboard
图片上传/下载相关 (2023-05-08)
如何将一个图片快速的保存/下载到本地,不是打开一个新的链接
?response-content-disposition=attachment # 图片地址做一个拼接
export const openATagToDownloadUrl = (url) => {
const a = document.createElement('a');
a.download = fileName;
a.href = url + '?response-content-disposition=attachment';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
补充一个方法:上传图片时,获取本地图片宽高
const getImgWidthAndHight = (file) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
return new Promise((resolve) => {
fileReader.onload = function () {
const img = new Image();
img.src = fileReader.result;
img.onload = function () {
const { width, height } = this;
resolve({
width,
height,
});
};
};
});
};
文件相关的魔术头 (16进制)
图片文件格式:
- JPEG(.jpg, .jpeg):0xFF 0xD8 0xFF
- PNG(.png):0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A
- GIF(.gif):0x47 0x49 0x46 0x38(后面可能跟随0x37 0x61或0x39 0x61)
- BMP(.bmp):0x42 0x4D
- WebP(.webp):0x52 0x49 0x46 0x46 0xx 0xx 0xx 0xx 0x57 0x45 0x42 0x50
视频文件格式:
- MP4(.mp4, .m4v, .f4v):0x00 0x00 0x00 0xx 0x66 0x74 0x79 0x70
- MOV(.mov):0x00 0x00 0x00 0xx 0x6D 0x6F 0x6F 0x76
- AVI(.avi):0x52 0x49 0x46 0x46 0xx 0xx 0xx 0xx 0x41 0x56 0x49 0x20 0x4C 0x49 0x53 0x54
- FLV(.flv):0x46 0x4C 0x56 0x01
- MKV(.mkv, .webm):0x1A 0x45 0xDF 0xA3
- 3GP(.3gp):0x00 0x00 0x00 0xx 0x66 0x74 0x79 0x70
- ASF(.asf, .wmv, .wma): 0x30 0x26 0xB2 0x75 0x8E 0x66 0xCF
前端 如何读取魔术头
const getImgMagicNumber = (file) => {
return new Promise((resolve) => {
const fileReader = new FileReader();
const blob = file.slice(0, 4);
fileReader.readAsArrayBuffer(blob);
fileReader.onload = function () {
// 读取 ArrayBuffer 数据
const arrayBuffer = fileReader.result;
// 将其转换为一个字节序列
const byteArray = new Uint8Array(arrayBuffer);
// 获取魔术头(这里我们取文件的前4个字节)
let magicNumber = "";
for (let i = 0; i < 4; i++) {
magicNumber += byteArray[i].toString(16);
}
console.log(`魔术头: ${magicNumber}`);
resolve(magicNumber);
};
});
};
多文件上传控制并发
// 文件数组
const files = [file1, file2, file3, ...];
// 并发上传的最大数量
const maxUploads = 3;
// 上传文件的方法
async function uploadFile(file) {
// 上传文件的代码
}
// 使用Promise.all()方法上传文件
async function uploadFiles() {
const results = [];
let index = 0;
while (index < files.length) {
const currentUploads = [];
for (let i = 0; i < maxUploads && index < files.length; i++) {
currentUploads.push(uploadFile(files[index++]));
}
results.push(...await Promise.all(currentUploads));
}
return results;
}
// 调用上传方法
uploadFiles().then(results => {
console.log(results);
}).catch(error => {
console.error(error);
});