preface

Generally speaking, you need to do type filtering for uploaded files to specify which types can and cannot be uploaded.

The easiest to think of, and relatively common, is to use the extension name of the file directly.

But extensions can be changed manually and imprecisely, such as changing a Word document from.doc to.png

The solution

After converting the uploaded file to binary form, the hexadecimal code of the first four header files can be obtained, according to which the uploaded file type can be accurately determined. If the upload format does not meet the requirements, the upload is processed on the client.

The HTML code

This section is for demonstration only. You can add fields according to actual business scenarios

<form id="form">
 <p><input type="file" name="file" multiple id='file'></p>
 <p><input type="button" value="Upload" id="btn"></p>
</form>
Copy the code

Js code

Access to the dom

let form = document.getElementById('form'); 
let btn = document.getElementById('btn'); 
let f = document.getElementById('file'); 
Copy the code

Gets the mime type of the file

More file types may refer to https://blog.csdn.net/weixin_33826268/article/details/94604439

function getFileMimeType(file) {
  const map = {
      'FFD8FFE0': 'jpg'.      '89504E47': 'png'.      '47494638': 'gif'. "52494646": 'webp'  }   const reader = new FileReader();  reader.readAsArrayBuffer(file);  return new Promise((resolve, reject) = > {  reader.onload = (event) = > {  try {  let array = new Uint8Array(event.target.result);  array = array.slice(0.4);  let arr = [...array]  let key = arr.map(item= > item.toString(16)  .toUpperCase()  .padStart(2.'0'))  .join(' ')  resolve(map[key])   } catch (e) {  reject(e);  }  };  }); } Copy the code

Upload the logic

btn.onclick = function () {
    if (f.files.length > 1) {
        for (const file of f.files) {
            upload(file)
        }
 } else {  upload(f.files[0])  } }  function upload(file) {  getFileMimeType(file).then(res= > {  if (res) {  let fd = new FormData(form);  let xhr = new XMLHttpRequest();  xhr.open("post".'/api/uploadFiles');  xhr.send(fd);  } else {  alert('File format does not meet upload requirements')  f.value = ' '  return  }   }).catch(err= > {  console.log(err)  }) } Copy the code

conclusion

File uploads are common, but precision may not be considered.

The sparingly used binary and type arrays, once again, make sense.

Hope you found this article helpful.


Love is fickle,

But move already hurt.

Thank you so much for reading my article,

I’m Cold Moon Heart. See you next time.