RGI
RGI

Reputation: 161

How to check upload file is txt or modified extension manually?

I created one web page where i want to upload only text file using JavaScript and it is working fine.

Using below JavaScript, it is checking upload file is txt or not?

<script>
  function checkExt() {
    if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
      alert("Please upload only .txt extention file");
      return false;
    }
  }
</script>

<form name="mainForm">
   <input type="file" name="myfile" onchange="checkExt();"/>
</form>

Live Demo Here

Problem: If I change extension of file .exe to .txt manually then it is also being upload because i'm checking file's extension only. So My question is how to protect from exe file (which is Manually changed to txt) to upload.

I want to stop upload exe, jar files which is changed or renamed forcefully or manually.

Upvotes: 4

Views: 2473

Answers (3)

Piyush Gupta
Piyush Gupta

Reputation: 2179

You need to verify modified exe file to txt on backend code. It is very simple code. Below program is checking file is executable or not either exe file changed to .txt extension.

Here we can read file for verification means file is contain bytes code or not

import java.io.File;
import java.io.FileInputStream;

public class TestExecutableFile {

    public static void main(String[] args) {

        byte[] firstBytes = new byte[4];
        try {
            FileInputStream input = new FileInputStream(new File("[filepath]/[filename]"));
            input.read(firstBytes);

            // Checking file is executable
            if (firstBytes[0] == 0x4d && firstBytes[1] == 0x5a) {
                System.out.println("Executable File");
            }else{
                System.out.println("Non Executable File");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 2

user3795616
user3795616

Reputation:

You just need to get file not with form.value but with form.files. There you can find such properties of file:

{
    lastModified: 1502265800000
    lastModifiedDate: Wed Aug 09 2017 11:03:20 GMT+0300 (EEST) {}
    name: "14ecdf0302f4bbc84cfbbf85b3b94013.jpg"
    size: 463225
    type: "image/jpeg"
}

Upvotes: 0

user2560664
user2560664

Reputation: 11

In my opinion client side validation on extension will not serve the purpose, you need to do MIME type validation on server side can solve the problem better.

Ref. article Using .NET, how can you find the mime type of a file based on the file signature not the extension

by ROFLwTIME

Upvotes: 0

Related Questions