How to Scan Files, Restrict File Types using JavaScript

Cloudmersive
2 min readJun 28, 2023

--

One effective way to improve your application’s threat profile is to limit your file upload types judiciously. Certain upload processes — like resume uploads, for example — only require a limited number of common file types, and allowing too large a variety of files only makes it easier for client-side threat actors to send disguised malware attacks through file upload portals.

Using the below code, you can simultaneously scan files for millions of virus and malware signatures and restrict file types to a comma-separated list of file extensions. You can also customize threat rules to block a variety of common hidden threat types, dramatically improving your application’s protection against file upload vulnerabilities.

To take advantage of this API, copy and paste the below code to structure your API call in JavaScript, and provide a free-tier API key to authenticate (this allows up to 800 API calls per month):

var data = new FormData();
data.append("inputFile", fileInput.files[0], "file");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});

xhr.open("POST", "https://api.cloudmersive.com/virus/scan/file/advanced");
xhr.setRequestHeader("allowExecutables", "<boolean>");
xhr.setRequestHeader("allowInvalidFiles", "<boolean>");
xhr.setRequestHeader("allowScripts", "<boolean>");
xhr.setRequestHeader("allowPasswordProtectedFiles", "<boolean>");
xhr.setRequestHeader("allowMacros", "<boolean>");
xhr.setRequestHeader("allowXmlExternalEntities", "<boolean>");
xhr.setRequestHeader("allowInsecureDeserialization", "<boolean>");
xhr.setRequestHeader("allowHtml", "<boolean>");
xhr.setRequestHeader("restrictFileTypes", "<string>");

xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");

xhr.send(data);

That’s all there is to it — now you can enjoy a much-improved threat profile while continuing to scale your application.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet